反序列化newtonsoft属性的动态对象名称 [英] Deserialize dynamic object name for newtonsoft property

查看:110
本文介绍了反序列化newtonsoft属性的动态对象名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我发送对某个API的请求时,它们返回了一个很棒的json,但是问题是,根据我提供的参数,对象名称始终是不同的,而数据结构却保持不变.所以我正在尝试使用Newtonsoft库将json转换为C#类.我发现做到这一点的唯一方法是使用JsonTextReader,但我想知道是否有更干净的方法来实现此目的,因此我查阅了文档,但在这方面找不到任何可帮助我的东西.我还尝试使用JValue.Parse进行动态对象映射,但是由于属性名称始终不同,因此对我没有帮助. 这是一个代码示例来说明此问题:

When I am sending request for a certain API, they return me a json which is awesome, but the problem is that depending on the parameters I provide, the object name is always different while the data structure remains the same. So I am trying to convert the json to a C# class using Newtonsoft library. The only way I've found to do this is by using JsonTextReader, but I'm wondering if there is a cleaner way of achieving this, I looked up the documentation and couldn't find anything to help me in that regard. I also tried using JValue.Parse for dynamic object mapping, but since the property name is always different, it doesn't help me. Here is a code sample to illustrate the problem:

{
"error": [],
  "result": {
    //This property name always changes
    "changingPropertyName": [
      [
        "456.69900",
        "0.03196000",
        1461780019.8014,
      ]]
    }

//C# mapping
public partial class Data
{
    [JsonProperty("error")]
    public object[] Error { get; set; }

    [JsonProperty("result")]
    public Result Result { get; set; }
}

public class Result
{
    [JsonProperty("changingPropertyName")]
    public object[][] changingPropertyName{ get; set; }
}

推荐答案

处理变量属性名称的一种方法是使用Dictionary<string, T>代替强类型类(其中T是您尝试捕获的变量属性).例如:

One way to deal with a variable property name is to use a Dictionary<string, T> in place of a strongly typed class (where T is the type of the variable property you trying to capture). For example:

public partial class Data
{
    [JsonProperty("error")]
    public object[] Error { get; set; }

    [JsonProperty("result")]
    public Dictionary<string, object[][]> Result { get; set; }
}

然后您可以从字典中获取第一个KeyValuePair,并且您将同时拥有变量属性的名称和该属性的可用值.

You can then get the first KeyValuePair from the dictionary and you will have both the name of the variable property and the value available from that.

string json = @"
{
  ""error"": [],
  ""result"": {
    ""changingPropertyName"": [
      [
        ""456.69900"",
        ""0.03196000"",
        1461780019.8014
      ]
    ]
  }
}";

var data = JsonConvert.DeserializeObject<Data>(json);

KeyValuePair<string, object[][]> pair = data.Result.First();
Console.WriteLine(pair.Key + ":");
object[][] outerArray = pair.Value;

foreach (var innerArray in outerArray)
{
    foreach (var item in innerArray)
    {
        Console.WriteLine(item);
    }
}

提琴: https://dotnetfiddle.net/rlNKgw

这篇关于反序列化newtonsoft属性的动态对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆