Reputation: 11331
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:
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:
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
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
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
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