1

Am calling an api which is returning below mentioned json.

{
    "salarySlipItems" : {
        "\"0\"" : {
            "value" : "11000.00",
            "description" : "Worth Salary",
            "sort" : "1"
        },
        "\"2\"" : {
            "value" : "500.00",
            "description" : "Other Income",
            "sort" : "3"
        },
        "\"3\"" : {
            "value" : "1354.84",
            "description" : "General Allowance",
            "sort" : "4"
        },
        "\"4\"" : {
            "value" : "500.00",
            "description" : "Telephone Allowance",
            "sort" : "5"
        },
        "\"7\"" : {
            "value" : "-2000.00",
            "description" : "Other Deductions",
            "sort" : "8"
        }
    },
    "decimalDigits" : "2",
    "status" : "1"
}

can any body guide me how can i parse that in c# asp.net? What i believe is salarySlipItems is a object having all properties. what are \"0\ \"2\ and so on..?

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
Singleton
  • 3,701
  • 3
  • 24
  • 37

1 Answers1

4

\"2\" in this case is a key of dictionary. It is just an escaped "2". In your JSON response all digits are presented as strings for some reason.

You can deserialize this JSON object using Dictionary:

public class Response
{
    public Dictionary<string, SlipItem> salarySlipItems { get; set; }
    public string decimalDigits { get; set; }
    public string status { get; set; }
}

public class SlipItem 
{
    public string value { get; set; }
    public string description { get; set; }
    public string sort { get; set; }
}

Then, you will be able to access it this way:

var response = JsonConvert.DeserializeObject<Response>(jsonString);
Console.WriteLine(response.status);

Accessing the dictionary item by key:

var item = response["\"2\""];
Console.WriteLine(item.value);

Enumerating through the dictionary:

foreach (var item in response) 
{
    Console.WriteLine("{0} has a description: {1}", item.Key, item.Value.description);
}
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • `Response` also needs `decimalDigits` and `status` – Rob Aug 12 '15 at 11:57
  • 1
    @Rob Yeah, just noticed it :) Updated. – Yeldar Kurmangaliyev Aug 12 '15 at 11:57
  • 1
    To expand on @Yeldar's answer - this is just a usual JSON object with properties that happen to have a number as their name. Since JSON objects are essentially just hashtables/dictionaries, and C# does not allow properties to start with a number, you'll need to use a dictionary to deserialize it. – Rob Aug 12 '15 at 12:00