JSON .NET deserialize into complex type with object key/name

旧街凉风 提交于 2019-12-13 16:43:27

问题


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

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

The code currently looks like:

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
}

And the class:

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

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?

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".


回答1:


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



回答2:


i tried to parse your JSON in the below line

var result = JsonConvert.DeserializeObject<Dictionary<string,  Dictionary<string,Order>>>(jsonString);

in your json string, you have first a key called "orders", this will match the string key if the outer dictionary, then the inner dictionary string key will match the order key and the value will be parsed as the order



来源:https://stackoverflow.com/questions/26141320/json-net-deserialize-into-complex-type-with-object-key-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!