WebApi绑定 - 将传入json的一部分反序列化为JToken

时间:2016-10-20 16:26:42

标签: c# json asp.net-web-api json.net json-deserialization

我正在尝试将此json反序列化为模型:

{
"settings": [
    {
    "name": "setting1",
    "value": {
        "key": "value"
        }
    }, 
    {
    "name": "setting2",
    "value": 10
 }
]
}

如您所见,我的value可以是简单值,如int或字符串,也可以是另一个json对象。

我的目标是将值反序列化为JTokenstring

我正在尝试使用Json.NET反序列化,因为我知道WebAPI在引擎盖下使用它。

这就是我的尝试:

  public class SettingsBatch
  {
    [JsonProperty(PropertyName = "settings")]
    public List<SettingInBatch> Settings { get; set; }
  }

  public class SettingsInBatch
 {
    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "value")]
    public object Value { get; set; }
 }

从我的测试中(请阅读内联评论):

[JsonProperty(PropertyName = "value")]
public string Value { get; set; } // deserialization fails when "value" is a JsonObject

[JsonProperty(PropertyName = "value")]
public JToken Value { get; set; } // deserialization fails always

[JsonProperty(PropertyName = "value")]
public Object Value { get; set; } // deserialization works fine, what's curios 
// is that if the value is a json object the Object type is JToken 
// (just that I have to cast it). If it's an int or a string
// obviously the type is int / string so I would have to 
//construct somehow a JToken. 

我怎样才能做到这一点?

0 个答案:

没有答案