从Json字符串解析JArray

本文关键字:JArray 字符串 Json | 更新日期: 2023-09-27 17:54:44

我想从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。

从Json字符串解析JArray

Count不是一个方法,它是一个属性。下面添加了一个例子,这样使用。

string json = @"
    [ 
        { ""test1"" : ""desc1"" },
        { ""test2"" : ""desc2"" },
        { ""test3"" : ""desc3"" }
    ]";
    JArray a = JArray.Parse(json);
     var _len = a.Count;

这里你会得到_len = 3

您的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;

在这里你不能将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;
    }