I need to deserialize the following JSON:
"response": {
"records": {
"record-1": { "id": "1", "name": "foo" },
"record-2": { "id": "2", "name": "foo" },
"record-3": { "id": "3", "name": "foo-bar" }
}
}
I am using the following C# code to deserialize the above JSON:
HttpWebRequest httpWebRequest
= System.Net.WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse httpWebResponse
= httpWebRequest.GetResponse() as HttpWebResponse)
{
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
throw new Exception(
string.Format("Server error (HTTP {0}: {1}).",
httpWebResponse.StatusCode,
httpWebResponse.StatusDescription)
);
Stream stream = httpWebResponse.GetResponseStream());
DataContractJsonSerializer dataContractJsonSerializer
= new DataContractJsonSerializer(typeof(MyResponseClass));
objResponse = dataContractJsonSerializer.ReadObject(stream);
if (objResponse == null)
return null;
}
And
[DataContract]
class MyResponseClass
{
[DataMember]
public Response response { get; set; }
}
[DataContract]
public class Response
{
[DataMember]
public Records records { get; set; }
}
[DataContract]
public class Records
{
[DataMember(Name = "record-1")]
Record record_1 { get; set; }
[DataMember(Name = "record-2")]
Record record_2 { get; set; }
[DataMember(Name = "record-3")]
Record record_3 { get; set; }
}
[DataContract]
public class Record
{
[DataMember]
public string id { get; set; }
[DataMember]
public string name { get; set; }
}
Surely there is a better way to get hold of the array of "record" under "records" that makes this scalable instread of defining each record individualy in the code. I know that a JSON reader can be used, but would prefer a simple deserialze routine.
I want to be able to deserialize the JSON into a list of records (e.g. List, how do I achieve this?
{and}around it.