【问题标题】:How can i parse json arrray with newtonsoft [duplicate]我如何用 newtonsoft 解析 json 数组 [重复]
【发布时间】:2014-08-08 05:40:12
【问题描述】:

我有这个 json 字符串:

[ 
   {f_id:100,r_id:200,count:2,c_id=111},
   {f_id:120,r_id:200,count:1,c_id=111 }
]


我想用 newtonsoft.json 解析 json 字符串。
我该怎么做?

我写了这段代码:

private void button1_Click(object sender, EventArgs e)
    {
        string json = @"[ 
{f_id:100,r_id:200,count:2,c_id=111},
{f_id:120,r_id:200,count:1,c_id=111 }
]";
        List<myClass> tmp = JsonConvert.DeserializeObject<List<myClass>>(json);
        int firstFId = tmp[0].f_id;
        label1.Text = firstFId.ToString();
        label2.Text = tmp[1].f_id.ToString();



    }

    public class myClass
    {
        public int f_id { get; set; }
        public int r_id { get; set; }
        public int count { get; set; }
        public int c_id { get; set; }


    }


但是有这个错误:

An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in    Newtonsoft.Json.dll

Additional information: Invalid JavaScript property identifier character: =. Path '[0].count', line 2, position 32.

【问题讨论】:

  • 你想把它解析成一个类,还是只是一个中间对象?
  • 有大量示例和已回答的问题。他们不是在帮助您解决问题吗?例如,stackoverflow.com/questions/18242429/…。如果不是,请更具体地说明您面临的确切问题。

标签: c# .net json


【解决方案1】:

创建一个代表数据的类。

public class MyClass {
   public int f_id { get; set; }
   public int r_id { get; set; }
   public int count { get; set; }
   public int c_id { get; set; }
}

将您的 json 字符串反序列化为 MyClass 列表。

List<MyClass> tmp = JsonConvert
    .DeserializeObject<List<MyClass>>(@"
                                        [
                                            {
                                            f_id: 100,
                                            r_id: 200,
                                            count: 2,
                                            c_id:111
                                            },
                                            {
                                            f_id: 120,
                                            r_id: 200,
                                            count: 1,
                                            c_id:111
                                            }
                                        ]
                                        ");

使用索引访问数据

int firstFId = tmp[0].f_id;

更新

您问题中的 json 字符串无效。

c_id=111 

应该是

c_id:111

【讨论】:

  • 谢谢大佬,我如何访问这个字段,例如 f_id[0]
  • 我更新了我的问题,请再次查看。
  • 您的 json 字符串无效。我的答案已更新
  • 感谢关注我的问题,您的帮助解决了我的问题,thanks.from iran.
猜你喜欢
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 2023-03-18
  • 1970-01-01
相关资源
最近更新 更多