Deserialize RestResponse to JSON data

1.9k Views Asked by At

how to deserialize the below Rest response to JSON response my rest response is in the format

{
"new_token":"fdffdsfdsfdsf",
"expires_in":400,
"login_type":"abc"
}

I have a POCO class as

public string NewToken { get; set; }
public string ExpiresIn { get; set; }
public string LoginType { get; set; }

How to store the rest response into the POCO classs

1

There are 1 best solutions below

11
Martin On BEST ANSWER

You just need to deserialise the JSON into your class.

Assuming your class is called Foo, just use the JavaScriptSerializer object:

Foo result = new JavaScriptSerializer().Deserialize<Foo>(json);

You will need to add a reference to System.Web.Extensions in order to access the JavaScriptSerializer.

EDIT

Following additional clarification regarding the mapping of the raw JSON property names to nice-looking .Net names, and assuming your class is called POCO, I suggest using the DataContractJsonSerializer as follows:

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

[DataContract()]
class POCO
{
    [DataMember(Name = "new_token")]
    public string NewToken { get; set; }

    [DataMember(Name = "expires_in")]
    public string ExpiresIn { get; set; }

    [DataMember(Name = "login_type")]
    public string LoginType { get; set; }
}

class SomeClass
{
    void DoSomething(string json)
    {
        MemoryStream reader;
        POCO output;
        DataContractJsonSerializer serializer;

        reader = new MemoryStream(Encoding.Unicode.GetBytes(json));
        serializer = new DataContractJsonSerializer(typeof(POCO));
        output = serializer.ReadObject(reader) as POCO;
    }
}