如何解析使用JavaScriptSerializer数字键JSON对象 [英] How to parse JSON objects with numeric keys using JavaScriptSerializer

查看:98
本文介绍了如何解析使用JavaScriptSerializer数字键JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像下面的一个目的是在C#中被反序列化。我想知道我怎么可以解析它。我想下面的这个例子这里,但我难倒我怎样才能让我的班认识到每个对象的键( 2 3 以下)。

JSON字符串下面基本上重新presents 2交易。我想每一笔交易再presentation转化为交易对象,并把它放入交易对象的数组。

  {
    2:{
        ID:2,
        USER_ID:59,
        offer_id:1234
    },
    3:{
        ID:3,
        USER_ID:59,
        offer_id:1234
    }
}
 

下面是我的类:

 公共类交易
{
    //发生的事情,因为这里的钥匙现场总是有什么不同?
}

公共类交易
{
    公众诠释ID {获得;组; }
    公众诠释USER_ID {获得;组; }
    公众诠释offer_id {获得;组; }
}
 

解决方案

它可与JObject在JSON.Net库来完成。

  VAR交易= JObject.Parse(JSON).PropertyValues​​()
                                      。选择(O => o.ToObject<交易>());
 

这应该可以解决问题。

I have an object like below to be deserialized in C#. I am wondering how I can parse it. I tried following this example here, but am stumped on how I can get my class to recognize the key of each object (the 2 and the 3 below).

The JSON string below basically represents 2 transactions. I would like to convert each transaction representation into a Transaction object and put it into an array of Transaction object.

{
    "2": {
        "id": "2",
        "user_id": "59",
        "offer_id": "1234"
    },
    "3": {
        "id": "3",
        "user_id": "59",
        "offer_id": "1234"
    }
}

Here are my classes:

public class Transactions
{
    // what goes here since the "key" field is always different?
}

public class Transaction
{
    public int id { get; set; }
    public int user_id { get; set; }
    public int offer_id { get; set; }
}

解决方案

It can be done with the JObject in JSON.Net library.

var transactions = JObject.Parse(json).PropertyValues()
                                      .Select(o => o.ToObject<Transaction>());

This should do the trick.

这篇关于如何解析使用JavaScriptSerializer数字键JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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