nm_help
nm_help

Reputation: 11

Deserializing Json using .Net

I have an external vendor API that returns JSON in this format

{"3":{"id":1,"name":"Scott Foo","age":55},
"59":{"id":2,"name":"Jim Morris","age":62}}

I am trying to deserialize it using the following code

[DataContract]
public class Name
{
    [DataMember]
    public int id { get; set; }

    [DataMember]
    public string name { get; set; }

    [DataMember]
    public int age{ get; set; }
}

Code to deserialize is

List<Name> nameList = Deserialize<List<Name>>(temp); 

where the Deserialize is defined as

public static T Deserialize<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();
    ms.Dispose();
    return obj;
}

The object returned in nameList is of zero count. Any idea how this JSON can be deserialized in .Net (i.e. not using Json.Net or any such third-party dll)?

Upvotes: 0

Views: 1381

Answers (2)

Matt G
Matt G

Reputation: 36

Here is one option.

//using System.Runtime.Serialization.Json;

public static dynamic Deserialize(string content)
{
    return new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject(content);
}

var f = Deserialize(json);
List<Name> list = new List<Name>();

foreach(var item1 in (Dictionary<string, object>) f)
{
    Dictionary<string, object> item2 = (Dictionary<string, object>) item1.Value;

    list.Add( new Name(){
        id = (int) item2["id"],
        name = (string) item2["name"],
        age = (int) item2["age"]
    });             

}

Upvotes: 2

L.B
L.B

Reputation: 116098

Your root object theoretically would be something like this

public class root
{
    public Name 3;
    public Name 59;
}

But 3 and 59 are not valid c# variable/field/property names (they are also dynamic). Therefore, you can not deserialize it to a class.

I see that you don't want to use Json.Net or any such third party dlls but this is how I parsed it using Json.Net

string json = @"{""3"":{""id"":1,""name"":""Scott Foo"",""age"":55},""59"":{""id"":2,""name"":""Jim Morris"",""age"":62}}";

JObject jobj = (JObject)JsonConvert.DeserializeObject(json);

foreach (JProperty user in jobj.Children())
{
    Console.WriteLine(user.Name + "==>" + user.Value["name"]);
}

and the output

3==>Scott Foo
59==>Jim Morris

Upvotes: 1

Related Questions