Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading JSON using JSON.NET

Tags:

json

c#

json.net

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)
like image 633
user2441297 Avatar asked Jun 01 '26 03:06

user2441297


1 Answers

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; }
}
like image 115
pajics Avatar answered Jun 02 '26 15:06

pajics