Allan Jiang
Allan Jiang

Reputation: 11331

Json Deserializer read objects to array

I am writing a deserializer callback method to parse some Json response in C# silverlight.

But the problem is the response is constructed by a bunch of objects and not in an array form.

To be specific, normally when we want to parse something from a json, if that's a list of object, it will look like this in some Json visualizer:

Json Array

we can do something like:

DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(ObjType[]));
ObjType[] response = (ObjType[])jsonSerializer.ReadObject(stream);

But now I have the Json file that the structure looks like this:

enter image description here

In this case I dont think I can parse it to an array since the objects are individual and not in an array structure.

A sample of the Json file is:

[
   {
      "Name":"Mike",
      "Gender":"male",
   },
   {
      "Name":"Lucy",
      "Gender":"Female ",
   },
   {
      "Name":"Jack",
      "Gender":"Male",
   }
]

So I am wondering if there is any way I can parse this kind of Json file to an array of defined object.

Upvotes: 2

Views: 6872

Answers (3)

samsanthosh2008
samsanthosh2008

Reputation: 91

public static T JSONDeserialize<T>(string json)
        {
            T obj = default(T);
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                obj = Activator.CreateInstance<T>();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                obj = (T)serializer.ReadObject(ms);
                ms.Close();
            }`enter code here`
            return obj;
        }

Upvotes: 0

L.B
L.B

Reputation: 116138

This works for me

string json = @"[
    {
        ""Name"":""Mike"",
        ""Gender"":""male""
    },
    {
        ""Name"":""Lucy"",
        ""Gender"":""Female ""
    },
    {
        ""Name"":""Jack"",
        ""Gender"":""Male""
    }
]";
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));

DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(ObjType[]));
ObjType[] response = (ObjType[])jsonSerializer.ReadObject(stream);

-

[DataContract]
public class ObjType
{
    [DataMember]
    public string Name;
    [DataMember]
    public string Gender;
}

Upvotes: 3

Raman Zhylich
Raman Zhylich

Reputation: 3697

[System.Runtime.Serialization.DataContractAttribute()]
public partial class RootClass
{

    [System.Runtime.Serialization.DataMemberAttribute()]
    public string Name;

    [System.Runtime.Serialization.DataMemberAttribute()]
    public string Gender;
}

    static void Main(string[] args)
    {
       var serializer = new DataContractJsonSerializer(typeof(RootClass[]));
        serializer.ReadObject(/*Input stream w/ JSON*/);

    }

Upvotes: 1

Related Questions