How to use DataContractJsonSerializer to parse a nested json object?

c#, json

Solution

The serialization engine understands complex types. It's safe for one DataContract type to reference another DataContract type.

(edit: I'm not entirely sure if protected setters are allowed)

[DataContract]
class IttResponse
{
    [DataMember(Name = "response")]
    public int Response { get; protected set; }

    [DataMember(Name = "result")]
    public IttResult Result { get; protected set; }
}

[DataContract]
public class IttResult
{
    [DataMember(Name = "package")]
    public IttPackage Package { get; set; }
}

[DataContract]
public class IttPackage
{
    [DataMember(Name = "token")]
    public string Token { get; set; }
}

Usage remains the same as before

IttResponse response = Deserialize(jsonText);

Problem

I have a json text like this: ``` { "response":200, "result": { "package": { "token":"aaa" } } } ``` I am using DataContractJsonSerializer to extract info from this above json. ``` public static T Deserialize<T>(string json) { var instance = Activator.CreateInstance<T>(); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) { var serializer = new DataContractJsonSerializer(instance.GetType()); return (T)serializer.ReadObject(ms); } } ``` I describe the classes as follow: ``` [DataContract] class IttResponse { [DataMember(Name = "response")] public int Response { get; protected set; } [DataMember(Name = "result")] public string Result { get; protected set; } } [DataContract] public class IttPackage { [DataMember(Name = "token")] public string Token { get; set; } } ``` Now, I tried to parse the json text as follow: ``` IttResponse response = Deserialize<IttResponse>(jsonText); IttPackage package = Deserialize<IttPackage>(response.token); ``` However, I always get error when parsing jsonText at the first line. Note: I am developing an application running on desktop written in C#, VS Ultimate 2013, .Net Framework 4.5 So, I think, I cannot use System.Web.Helpers, or System.Web.Script.Serialization to parse.

Original source