【问题标题】:How to parse unreadable json?如何解析不可读的json?
【发布时间】:2021-09-16 01:29:08
【问题描述】:
{
    "12": {
        "_agicId": 2,
        "_index_": "",
        "_seq": 1
    },
    "11": {
        "_agicId": 1,
        "_index_": "",
        "_seq": 2
    },
    "10": {
        "_agicId": 0,
        "_index_": "",
        "_seq": 3
    }
}

我得到一个像上面这样的 json 字符串,但我不知道“12”“11”“10”,我如何解析这个 json 得到 _seq & agicId?

var Name = JObject.Parse(r);
int Count = Name.Count;
for (int i = 0; i < Name.Count; i++)
{
    // how can i get  "11"{"agicId":0}
}

【问题讨论】:

标签: c# json


【解决方案1】:

为此创建一个如下所示的模型类:

class Test
    {
        public int _agicId { get; set; }
        public string _index_ { get; set; }
        public string _seq { get; set; }
    }

然后像下面这样读取 json。我已从文件中读取。您也可以从字符串中读取。在键中,您将获得 11、12 等...而在值中,您将获得具有“agicId”等值的 Text 类...

using (StreamReader r = new StreamReader("data.json"))
            {
                string jsonString = r.ReadToEnd();
                JObject jsonObj = JObject.Parse(jsonString);

                var k = JsonConvert.DeserializeObject<Dictionary<string, Test>>(jsonString);
                /*
                A very good suggestion by Jon Skeet. No need of this foreach loop. Instead of criticising he has suggested a better solution.
                foreach(var item in jsonObj)
                {
                    string key = item.Key;
                    var value =  JsonConvert.DeserializeObject<Test>(item.Value.ToString());                    

                }*/
            }

【讨论】:

  • 糟糕的想法..你正在反序列化一些东西来序列化它并再次反序列化
  • 使用JsonConvert&lt;Dictionary&lt;string, Test&gt;&gt;(jsonString);会更简单
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多