JSON .NET使用对象键/名称反序列化为复杂类型 [英] JSON .NET deserialize into complex type with object key/name

查看:69
本文介绍了JSON .NET使用对象键/名称反序列化为复杂类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用Newtonsoft JSON .NET进行大多数API/JSON的使用,并且通常将其反序列化或转换为复杂的类型以便于使用.问题在于,我似乎找不到一种处理具有动态名称(即每次都不同)的对象的好方法.

I'm using Newtonsoft JSON .NET in my project for most of my API/JSON usage, and usually deserialize or convert into a complex type for easier usage. The problem is that I can't seem to figure out a good way to handle an object with a name/key that is dynamic (ie it is different every time).

我需要解析的JSON并非完全符合标准,但目前我无法更改.相关的JSON在下面(我没有包括整个结构).

The JSON I need to parse isn't exactly made to standard, but currently it's not in my power to change it. The relevant JSON is below (I didn't include the whole structure).

"orders": {
  "32f5c31d-a851-40cf-a8bb-2fea4bd27777": {
    "orderId": "ord12345",
    "state": "new",
    "sellAmount": "200",
    "paymentMethod": "buyMethod2",
    "email": "example@email.com",
    "pinOrPhonenumber": "180012345",
    "timestamp": "2014-10-01T07:13:33.868Z"
  },
  "123d98d5-19b1-4cb3-8ab3-b991650b134c": {
    "orderId": "ord12346",
    "state": "pending",
    "sellAmount": "1200",
    "paymentMethod": "buyMethod2",
    "email": "example@email.com",
    "pinOrPhonenumber": "180012345",
    "timestamp": "2014-10-01T07:13:33.868Z"
  }
}

当前代码如下:

var jResponse = Newtonsoft.Json.Linq.JObject.Parse(rResponse.Content);
var jOrders = jResponse["orders"];
foreach (var jChild in jOrders) {
   string sOrderGUID = ""; //The name/key of the object
   var jOrder = jChild.First.ToObject<Order>();
   //Handle the order data, etc
}

和班级:

public class Order {

  [JsonProperty("orderId")]
  public string sOrderID { get; set; }

  [JsonProperty("state")]
  public string sState { get; set; }

  [JsonProperty("sellAmount")]
  public decimal nAmount { get; set; }

  [JsonProperty("paymentMethod")]
  public string sPaymentMethod { get; set; }

  [JsonProperty("email")]
  public string sEmail { get; set; }

  [JsonProperty("phonenumber")]
  public string sPhonenumber { get; set; }

  [JsonProperty("paymentMessage")]
  public string sPaymentMessage { get; set; }

  [JsonProperty("timestamp")]
  public DateTime dTimestamp { get; set; }
}

曾经希望将其转换为JObject并使用Properties来获取密钥,但是如果可能的话,我更喜欢一种更简洁的方法.有指针吗?

Been looking into converting it into a JObject and using the Properties to get the key out, but I would prefer a cleaner way to do it if possible. Any pointers?

更新:Dictionary解决方案对于订单情况效果很好,但是当我尝试将相同的方法应用于JSON的另一部分时,我遇到了另一个问题.

Update: The Dictionary solution worked out well for the order situation, but I then ran into another problem when trying to apply the same method to another part of the JSON.

"rates": {
    "sek": {
        "name": "Swedish Krona",
        "usd": {
            "name": "US Dollar",
            "rates": {
                "2014-10-01T12:14:26.497Z": 0.138794,
                "2014-10-01T12:17:51.143Z": 0.138794,
                "2014-10-01T12:26:26.827Z": 0.138794,
                "2014-10-01T12:51:03.347Z": 0.138794
            }
        }
    },
    "usd": {
        "name": "US Dollar",
        "sek": {
            "name": "Swedish Krona",
            "rates": {
                "2014-10-01T12:14:28.763Z": 7.20753,
                "2014-10-01T12:17:52.667Z": 7.20753,
                "2014-10-01T12:26:28.477Z": 7.20753,
                "2014-10-01T12:51:04.963Z": 7.20753
            }
        }
    }
}

问题是我需要收集名称"值以及其他值,但是货币代码是可变的.考虑使用嵌套词典,但似乎无法获取名称".

The problem being that I need to collect the "name" value as well as the rest but the currency code is variable. Considered using nesting Dictionary, but can't seem to get a way to capture the "name".

推荐答案

对此,词典是一个更好的答案.

Yes dictionary is a better answer for this.

var orderWrapper = JsonConvert.DeserializeObject<OrderWrapper>(json);
IEnumerable<Order> orders = result.GetOrders();

public class OrderWrapper
{
    [JsonProperty("orders")] 
    private Dictionary<string, Order> _orders;

    public IEnumerable<Order> GetOrders()
    {
        return _orders.Values;
    }
}

这篇关于JSON .NET使用对象键/名称反序列化为复杂类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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