3

如何使用 JSON.NET 反序列化以下 JSON:

{
"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"}
}

我有以下代码(但问题可能出在'extra_params' - 它不是字符串)。我想过为“extra_params”创建新类,但问题是“extra_params”中的数据可能会改变。

我根本不需要阅读 EXTRA_PARAMS。我需要的所有信息都来自前 3 个 JSON 变量。

我的代码:

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);

其中有效负载 = 粘贴在第一个引号中的字符串

编辑:我现在得到的错误:

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)
4

4 回答 4

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; }
}
于 2013-06-26T10:46:28.120 回答
1

您可以通过使用更进一步dynamic

 dynamic x = JsonConvert.DeserializeObject(payload);
 var data = new RecData1()
                 {
                     uid = x.uid,
                     amount = x.amount,
                     adjusted_amount = x.adjusted_amount
                 };
于 2013-06-26T10:30:32.340 回答
0

如果你想得到extra_params,你可以试试这个:

public class RecData1
{
    public string uid { get; set; }
    public int amount { get; set; }
    public int adjusted_amount { get; set; }
    public Dictionary<string,string> extra_params { get; set; }
}

var data = JsonConvert.DeserializeObject<RecData1>(payload);
于 2013-06-26T10:59:19.047 回答
0

我相信问题是因为你额外的参数不是你的json中的字符串。

它应该是这样的:

"extra_params": {"string........................................."}

它应该工作。或者您需要更改您的类以考虑具有 json 中所有属性的另一个对象。

于 2013-06-26T10:25:14.113 回答