Reading JSON using JSON.NET

10,140

Solution 1

First issue you have is that adjusted_amount is not an int, but a decimal (also problem with localization can occur there).

Secondly, you could in your class RecData1 remove string extra_params and that will fix it.

{
"adjusted_amount":200,
"amount":2,
"uid":"admin",
"extra_params": {"uid":"admin","ip":"83.26.141.183","user_agent":"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/537.36"}
}

public class RecData1
{
    public string uid { get; set; }
    public int amount { get; set; }
    public int adjusted_amount { get; set; }
    //public string extra_params { get; set; }
}

Solution 2

You can have one more step forward by using dynamic:

 dynamic x = JsonConvert.DeserializeObject(payload);
 var data = new RecData1()
                 {
                     uid = x.uid,
                     amount = x.amount,
                     adjusted_amount = x.adjusted_amount
                 };
Share:
10,140

Related videos on Youtube

user2441297
Author by

user2441297

Updated on September 15, 2022

Comments

  • user2441297
    user2441297 over 1 year

    How to deserialize the following JSON using JSON.NET:

    {
    "adjusted_amount":200.0,
    "amount":2,
    "uid":"admin",
    "extra_params": {"uid":"admin","ip":"83.26.141.183","user_agent":"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/537.36"}
    }
    

    I have the following code (but the problem is probably with 'extra_params' - it is not a string). I thought about creating new class for 'extra_params' but the problem is that the data in 'extra_params' may change.

    I DONT NEED TO READ EXTRA_PARAMS AT ALL. All info I need, I get from the first 3 JSON variables.

    My code:

    public class RecData1
    {
        public string uid { get; set; }
        public int amount { get; set; }
        public int adjusted_amount { get; set; }
        public string extra_params { get; set; }
    }
    
    var data = JsonConvert.DeserializeObject<RecData1>(payload);
    

    where payload = string pasted in the first quotation

    EDIT: The error I get now:

    Error reading string. Unexpected token: StartObject. Path 'extra_params', line 1,     position 28.
    
    at Newtonsoft.Json.JsonReader.ReadAsStringInternal()
    at Newtonsoft.Json.JsonTextReader.ReadAsString()
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
    
  • user2441297
    user2441297 almost 11 years
    I just figured that out and I was on the point of sending my own answer. But you were first! (The problem with the INT)