3

I have a JSON that returns

{
    "access_token": "",
    //....
}

I would like to map it to AccessToken rather than access_token.

Using JSON.NET, one can write

[JsonProperty("access_token")]
public string AccessToken{ get; set; }

Is there an equivalent in ASP.NET framework? I do not want JSON.NET dependency here.

naveen
  • 53,448
  • 46
  • 161
  • 251
  • 1
    This maybe what you are looking for. The JavaScriptConvert answer will allow you to put the JSON to your own custom object. [The second answer by Paul Alexander](http://stackoverflow.com/questions/1100191/javascriptserializer-deserialize-how-to-change-field-names) – Aaron Sep 27 '15 at 14:45

1 Answers1

5

You need to use DataContractJsonSerializer and DataContract,DataMember as below:

public static class SerializationHelper
{
    /// <summary> Deserializes Json string of type T. </summary>
    public static T DeserializeJsonString<T>(string jsonString)
    {
        T tempObject = default(T);

        using (var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            tempObject = (T) serializer.ReadObject(memoryStream);
        }

        return tempObject;
    }
}


[DataContract]
public class DataObject
{
    [DataMember(Name = "user_name")]
    public string UserName { get; set; }

    [DataMember(Name = "access_token")]
    public string AccessToken { get; set; }
}

Usage:

var json = "{\"user_name\":\"John Doe\",\"access_token\":\"ABC123\"}";
var data = SerializationHelper.DeserializeJsonString<DataObject>(json);
Yuriy A.
  • 750
  • 3
  • 19