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)
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With