Reputation: 153
I have a C# application, it send a http Request and received a response from WebServer.
This is the code and it found:
String url = "http://myurl";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "GET";
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
log.Info(httpResponse);
using (var reader = new StreamReader(httpResponse.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
ResponseJSON myojb = (ResponseJSON)js.Deserialize(objText, typeof(ResponseJSON));
}
}
objText contains that response
"{"status":1,
"message":"Ok",
"people":[
{
"fiscalCode":"ASSISTITO2",
"name":"Marco",
"surname":"Puzzolante",
"sex":"M",
"bornDate":null,
"cityCode":null
},
{"fiscalCode":"PLMLCU",
"name":"Luca",
"surname":"Palumbo",
"sex":"M",
"bornDate":"1983-04-22T00:00:00",
"cityCode":"FO"
}
]
}"
Now I have this Object "ResponseJSON". It have populate onlky two fields (status and message). The ResponseJSON is:
public class ResponseJSON
{
public int status { set; get; }
public String message { set; get; }
public List<Person> person { set; get; }
}
This Object don't have populate a List of Person.
The object Person is:
public class Person
{
public String fiscalCode { set; get; }
public String name { set; get; }
public String surname { set; get; }
public String sex { set; get; }
public String bornDate { set; get; }
public String cityCode { set; get; }
public String provinceCode { set; get; }
public String username { set; get; }
public String bloodGroup { set; get; }
}
Where is my error?
Can we help me?
Reguards
Upvotes: 1
Views: 2209
Reputation: 21265
Your ResponseJSON
class does not match your JSON.
Change the person
property to people
to reflect the JSON.
public class ResponseJSON
{
public int Status { set; get; }
public String Message { set; get; }
public List<Person> People { set; get; }
}
JavaScriptSerializer
will deserialize case insensitive, so you can PascalCase your properties if your JSON is camelCase.
Also there is a generic overload of Deserialize
:
var myojb = js.Deserialize<ResponseJSON>(objText);
Upvotes: 4