chipbk10
chipbk10

Reputation: 5955

How to use DataContractJsonSerializer to parse a nested json object?

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.

Upvotes: 4

Views: 10714

Answers (2)

Steven Liekens
Steven Liekens

Reputation: 14088

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);

Upvotes: 6

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12324

You can include your IttPackage into IttResposne object so that you will only parse json one time. Moreover, I don't think you can use protected modifier for property's set method, so try removing it.

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

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

Upvotes: 1

Related Questions