I am using an API that returns me the result JSON formatted like this:
{
"undefined":{
"theresult":{
"back_1s":{
"consumed":1115287.58,
"min_cons":28789,
"max_cons":1086498.58,
"totalobjs":12683,
"totalproces":4298
},
"back_10s":{
"consumed":1115287.58,
"min_cons":28789,
"max_cons":1086498.58,
"totalobjs":12683,
"totalproces":4298
}
}
}
}
The first thing I did was creating a C# object that has 5 properties for each of the JSON's values. Then I de-serialized the JSON string into an array of this new object.
However I have no idea what back_1s
is, and what it will represent in C#,not to mention theresult
and the undefined
.
I just see no way for me to de-serialize it without help.
This is how I de-serialize in C#
List<NEWOBJECT> gooddata = JsonConvert.DeserializeObject<List<NEWOBJECT>>(jsonstring);
EDIT #1:
I am getting this error when I deserialize in C#
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'mvcAndrew.Controllers.NEWOBJECT[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Easiest ist to generate the C# Classes from JSON: http://json2csharp.com/
If you deserialize it use the generated RootObject class (or rename the class) that should do the trick.
This will generate two classes for Back1s / Back10s - you can still use only one class (delete the other one) and edit the "Theresult" class corresponding (for example, I renamed Back1s to BackClass and deleted the Back10s class)
public class Theresult
{
public BackClass back_1s { get; set; }
public BackClass back_10s { get; set; }
}
You can also use Newtonsoft.json.
var files = JObject.Parse(YourJsonHere);
var recList = files.SelectToken("$..theresult").ToList();
foreach (JObject item in recList.Children())
{
string values = item["consumed"].ToString();
// You can get other values here
}
Need to create a class structure same as your return object may be kind of
public class backDetails
{
public double consumed { get; set; }
public double min_cons { get; set; }
public double max_cons { get; set; }
public double totalobjs { get; set; }
public double totalproces { get; set; }
}
public class TheResult
{
public backDetails back_1s { get; set; }
public backDetails back_10s { get; set; }
}
public class MyClass
{
public TheResult theresult { get; set; }
}
Then this will work
List<MyClass> gooddata = JsonConvert.DeserializeObject<List<MyClass>>(jsonstring);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.