Reputation: 293
I want to parse a JArray from a Json String. For that I have this code:
JObject myjson = JObject.Parse(theJson);
JArray nameArray = JArray.Parse(theJson);
_len = nameArray.Count();
The theJsonString is the following
"{\"0\": [-26.224264705882351, 0.67876838235294112, -38.031709558823529, 46.201555361781679],
\"1\": [-26.628676470588236, 2.4784007352941178, -37.377297794117645, 45.959670050709867]}"
The problem is that when I debug I have nameArray always null and _len=0. Can you help to find the error.
Upvotes: 4
Views: 18949
Reputation: 2741
Your Json is invalid
valid Json
{"0": [-26.224264705882351, 0.67876838235294112, -38.031709558823529, 46.201555361781679],
"1": [-26.628676470588236, 2.4784007352941178, -37.377297794117645, 45.959670050709867]}
Use this code to deserialize json
var myjson = JsonConvert.DeserializeObject <Dictionary<int, double[]>>(theJson);
int _len = myjson.Count;
Upvotes: 1
Reputation: 1018
FYI Count is not a method, it is a property. Added below an example so use like this.
string json = @"
[
{ ""test1"" : ""desc1"" },
{ ""test2"" : ""desc2"" },
{ ""test3"" : ""desc3"" }
]";
JArray a = JArray.Parse(json);
var _len = a.Count;
Here you will get value of _len = 3
Upvotes: 3
Reputation: 449
Here you can't parse your json into a JArray. But you can use the JsonObject just like an array if you want to keep your json string.
Here is some bad code, but it can give you some ideas, i assume that the number in your json string is some ID and start to 0 to 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)
Here is a bad function ( bad code, while is disgusting) but it works and you can understand what you can do with it ( assuming the id is 0 to XXX ) :
public static int getCountMyJson(JObject json)
{
int i = 0;
while(json.GetValue(i+"") != null)
{ i++; }
return i;
}
Upvotes: 0