-2

I have the json String

{
    "isSuccess": true,
    "responseMessage": "Voucher Code is valid!",
    "responseData": {
        "vouchername": "COMPANY",
        "vouchercode": "sss12",
        "vouchervalue": "100"
    }
}

How can i read this JSON data in c# code?

Mohit S
  • 13,723
  • 6
  • 34
  • 69
selvakumar
  • 73
  • 3
  • 12
  • 1
    See http://www.newtonsoft.com/json/help/html/deserializeobject.htm and http://stackoverflow.com/questions/2546138/deserializing-json-data-to-c-sharp-using-json-net – dbc Jan 29 '16 at 04:30

3 Answers3

1

Use JsonConvert.DeserializeObject() to deserialize this string into a Class Type then simply access its properties in the usual way.

public class Rootobject
{
    public bool isSuccess { get; set; }
    public string responseMessage { get; set; }
    public Responsedata responseData { get; set; }
}

public class Responsedata
{
    public string vouchername { get; set; }
    public string vouchercode { get; set; }
    public string vouchervalue { get; set; }
}

Then you can access the values like this

var results = JsonConvert.DeserializeObject<Rootobject>(json);
var strResponseMessage = results.responseMessage ;
var strVoucherName = results.responseData.vouchername;

The links provided by dbc are very helpful. Do have a look on it

Mohit S
  • 13,723
  • 6
  • 34
  • 69
0
  1. Create c# class that can deserialize your json string. You can do it here json2csharp.com
  2. Add newtonsoft json Nuget package to your solution.
  3. Then you can deserialize your string like,

var requestToken = JsonConvert.DeserializeObject<(RequestToken)>(Content);

where, RequestToken is your C# class name and Content is your json string.

Thanks.

DSA
  • 720
  • 2
  • 9
  • 30
0

You can deseralize your json data in different ways.Either make a class for json values or use a dictionary and access data from it after serialization.

For this code You need to add a reference to your project to "System.Web.Extensions.dll"

using System.Web.Script.Serialization;
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string,dynamic>>(jsonText);

You can access your desired fields as

bool isSuccess = Convert.ToBool(dict["isSuccess"]);
string vouchername = Convert.ToString(dict["responseData"]["vouchername"]);
mck
  • 978
  • 3
  • 14
  • 38
  • For this code You need to add a reference to your project to "System.Web.Extensions.dll" – mck Jan 29 '16 at 05:02