以JSON格式解析响应
本文关键字:响应 格式 JSON | 更新日期: 2023-09-27 18:19:18
{
"response":{
"code":200,
"message":"OK",
"data":[
{
"user":{
"id":"564564",
"firstName":"XYZ",
"lastName":"J.",
"photo":"https:'/'/img-s.example.com'/userpix_thumbs'/48935_12545435354.png",
"gender":"male",
"homeCity":"Algonquin, IL",
"contact":{
}
},
"lastCheckin":34634543532
},
{
"user":{
"id":"3254353",
"firstName":"PQR",
"lastName":"Black",
"photo":"https:'/'/img-s.example.com'/userpix_thumbs'/TJZE1FSTWBE5JA11.jpg",
"gender":"male",
"homeCity":"Chicago, IL",
"relationship":"friend",
"contact":{
}
},
"lastCheckin":3534523422345
}
]
}
}
以上为JSON
的响应。我无法从上面的响应解析"用户"内容。它总是返回0
而不是firstName
和lastName
字段。请帮助。下面是我的代码。
FSQAPIRec_CheckIn_Results g1 = new FSQAPIRec_CheckIn_Results();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string json = sr.ReadToEnd();
sr.Close();
g1 = JSONHelper.Deserialise<FSQAPIRec_CheckIn_Results>(json);
if (g1.response.message == "OK")
{
List<FSQCheckIn_Data> obj = g1.response.data;
for (int i = 0; i < obj.Count(); i++)
{
List<FSQCheckIn_UserData> obj1 = obj[i].user;
for (int j = 0; j < obj1.Count(); j++)
lbl_Resent_Chechin.Text += (j + 1) + ") " + obj1[j].firstName + " " + obj1[j].lastName + "<br/><br/>";
}
}
public class JSONHelper
{
public static T Deserialise<T>(string json)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serialiser = new DataContractJsonSerializer(typeof(T));
return (T)serialiser.ReadObject(ms);
}
}
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
[Serializable]
[DataContract]
public class FSQAPIRec_CheckIn_Results
{
[DataMember]
public RecCheckIn_Response response { get; set; }
}
[Serializable]
[DataContract]
public class RecCheckIn_Response
{
[DataMember]
public string code { get; set; }
[DataMember]
public string message { get; set; }
[DataMember]
public List<FSQCheckIn_Data> data { get; set; }
}
[Serializable]
[DataContract]
public class FSQCheckIn_Data
{
[DataMember]
public List<FSQCheckIn_UserData> user { get; set; }
}
[Serializable]
[DataContract]
public class FSQCheckIn_UserData
{
[DataMember]
public string firstName { get; set; }
[DataMember]
public string lastName { get; set; }
[DataMember]
public string photo { get; set; }
}
user
项不是一个列表,它是一个单独的对象。
...
if (g1.response.message == "OK") {
List<FSQCheckIn_Data> obj = g1.response.data;
for (int i = 0; i < obj.Count(); i++) {
FSQCheckIn_UserData obj1 = obj[i].user;
lbl_Resent_Chechin.Text += "1) " + obj1.firstName + " " + obj1.lastName + "<br/><br/>";
}
}
...