Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...