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.

dbc
  • 104,963
  • 20
  • 228
  • 340
Craton
  • 23
  • 1
  • 3

1 Answers1

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[];
carlosfigueira
  • 85,035
  • 14
  • 131
  • 171
Marksl
  • 822
  • 8
  • 15
  • 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). – Craton Nov 22 '12 at 05:57