2

I'm having issues with deserializing some json with C#.

Suppose this is a snippet of the json I'm being sent (repeated many times, but nothing else other than id/name):

[
    {
    "id":0,
    "name":"N/A"
    },
    {
        "id":1,            
        "name":"Annie"            
    },
    {
        "id":2,            
        "name":"Olaf"            
    }    
]

If the top level was named, I'd do something like

[DataContract]
public class ChampList
{
    [DataMember(Name = "SOMENAME")]
    public ElophantChamp[] ElophantChamps { get; set; }
}

[DataContract]
public class ElophantChamp
{
    [DataMember(Name = "id")]
    public int ID { get; set; }

    [DataMember(Name = "name")]
    public string Name { get; set; }

}

and then deserialize it by calling this:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(ChampList));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
ChampList jsonResults = objResponse as ChampList;

But in the case where there is no top level container object and I can't have blank datamember name, what do I do? I just get a null value if I leave the DataMember unnamed (i.e. leave it as just [DataMember]), which I would take to indicate that couldn't parse it correctly.

No errors are thrown and the sesponse stream is populated with exactly what I expect.

From what I can tell searching around and basic reasoning, I shouldn't be very far off from where I need to be. There's just something I'm doing wrong with handling that highest level.

1 Answer 1

3

Does it work without the parent class ChampList?

DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(ElophantChamp[]));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
ElophantChamp[] jsonResults = objResponse as ElophantChamp[];
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, perfectly. I'd tried that, but didn't realize I could do it as (typeof(ElophantChamp[]) and had only tried typeof(ElophantChamp) (which failed).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.