【问题标题】:Parsing JArray from Json string?从Json字符串解析JArray?
【发布时间】:2016-07-05 20:15:07
【问题描述】:

我想从一个 Json 字符串中解析一个 JArray。为此我有这个代码:

        JObject myjson = JObject.Parse(theJson);
        JArray nameArray = JArray.Parse(theJson);                 
        _len = nameArray.Count();

theJsonString 如下

"{\"0\": [-26.224264705882351, 0.67876838235294112, -38.031709558823529, 46.201555361781679],
  \"1\": [-26.628676470588236, 2.4784007352941178, -37.377297794117645, 45.959670050709867]}"

问题是,当我调试时,nameArray 始终为 null 并且 _len=0。 你能帮忙找出错误吗?

【问题讨论】:

标签: c# json json.net


【解决方案1】:

仅供参考 Count 不是一种方法,它是一种属性。 在下面添加了一个示例,因此可以这样使用。

string json = @"
    [ 
        { ""test1"" : ""desc1"" },
        { ""test2"" : ""desc2"" },
        { ""test3"" : ""desc3"" }
    ]";

    JArray a = JArray.Parse(json);
     var _len = a.Count;

在这里你会得到 _len = 3

【讨论】:

    【解决方案2】:

    你的 Json 无效

    有效的 Json

    {"0": [-26.224264705882351, 0.67876838235294112, -38.031709558823529, 46.201555361781679],
      "1": [-26.628676470588236, 2.4784007352941178, -37.377297794117645, 45.959670050709867]}
    

    使用此代码反序列化 json

        var myjson = JsonConvert.DeserializeObject <Dictionary<int, double[]>>(theJson);
    int _len = myjson.Count;
    

    【讨论】:

      【解决方案3】:

      在这里你不能将你的 json 解析成一个 JArray。但是如果你想保留你的 json 字符串,你可以像使用数组一样使用 JsonObject。

      这是一些不好的代码,但它可以给你一些想法,我假设你的 json 字符串中的数字是一些 ID 并且从 0 到 X 开始:

              //Your json, the id is the value 0..1..2
              string json = "{\"0\": [-26.224264705882351, 0.67876838235294112, -38.031709558823529, 46.201555361781679],
                               \"1\": [-26.628676470588236, 2.4784007352941178, -37.377297794117645, 45.959670050709867]}";
      
              //Create json object
              JObject myjson = JObject.Parse(json);
      
              //Get the number of different object that you want to get from this json
              int count = getCountMyJson(myjson);
      
              //Create your Jarray
              JArray nameArray = new JArray();
      
              //Get the value from the json, each different value , start to 0 and going to the maximum value
              for (int i = 0; i < count; i++)
              {
                 if(myjson[i+""] != null)
                  nameArray.Add(myjson[i + ""]);
              }
              //Now you have a JArray that match all your json value ( here the object 0 and 1)
      

      这是一个糟糕的功能(糟糕的代码,虽然很恶心)但它可以工作,你可以理解你可以用它做什么(假设 id 是 0 到 XXX):

       public static int getCountMyJson(JObject json)
          {
              int i = 0;
            while(json.GetValue(i+"") != null)
              { i++; }
              return i;
          }
      

      【讨论】:

        猜你喜欢
        • 2018-04-13
        • 2021-10-29
        • 2021-06-28
        • 2016-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多