I am deserializing some JSON into a list of the type Data1.
The class:
public class RootObject
{
public List<Data1> data { get; set; }
public string status { get; set; }
public int requested { get; set; }
public int performed { get; set; }
}
public class Data1
{
public List<ClioFolder> data { get; set; }
public int status { get; set; }
}
public class ClioFolder
{
public int id { get; set; }
public string name { get; set; }
public Parent parent { get; set; }
}
public class Parent
{
public int id { get; set; }
public string name { get; set; }
}
The Json:
{
"data": [
{
"data": [
{
"id": 66880231,
"name": "root",
"parent": null
},
{
"id": 68102146,
"name": "Dummy",
"parent": {
"id": 66880231,
"name": "root"
}
}
],
"status": 200
}
],
"status": "completed",
"requested": 10,
"performed": 10
}
Using this command:
List<Data1> allData = JsonConvert.DeserializeObject<RootObject>(content).data;
This is working fine, but what I really need is the data from within the two "data" objects in it's own list too. I thought I would be able to do something like:
List<ClioFolder> allClios = allData.data;
But this doesn't work. I did also try deserailizing from the JSON directly into this second list, but this doesn't work either:
List<Cliofolder> allClios = JsonConvert.DeserializeObject<RootObject>(content).data.data;
What would be the correct way to achieve this?
It's a list. your should use:
List<ClioFolder> test = allData.FirstOrDefault()?.data;
tried to make a clean example. and im pretty sure this can be achieved with linq but i can't think of how to flatten a multidimensional array in linq right now.
List<ClioFolder> allClios = new List<ClioFolder>();
foreach(Data1 data in allData)
{
allClios.AddRange(data.data.ToArray());
}
Related
I have the following JSON string
{
"data": [
{
"symbol": "1COV.GE",
"exposure": "0",
"makerExposure": "-2028",
"takerExposure": "2028",
"makerPnl": "447.6688",
"takerPnl": "-447.6688",
"makerPositions": [
{
"name": "IB_001",
"position": "-2028",
"vwap": "47.41",
"pnl": "447.6688"
}
],
"takerPositions": [
{
"name": "MT5_1",
"position": "2028",
"vwap": "47.41",
"pnl": "-447.6688"
}
]
},
{
"symbol": "A",
"exposure": "0",
"makerExposure": "-10",
"takerExposure": "10",
"makerPnl": "-4.6",
"takerPnl": "4.6",
"makerPositions": [
{
"name": "IB_002",
"position": "-10",
"vwap": "136.78",
"pnl": "-4.6"
}
],
"takerPositions": [
{
"name": "MT5_1",
"position": "10",
"vwap": "136.78",
"pnl": "4.6"
}
],
"total": 2
}
}
And my goal is to serialize it into a List of object from the NODE "Data":
I have the classes that map the data node fields:
public class Positions
{
public string name { get; set; }
public string position { get; set; }
public string vwap { get; set; }
public string pnl { get; set; }
}
public class ExPositions
{
public string symbol { get; set; }
public string exposure { get; set; }
public string makerExposure { get; set; }
public string takerExposure { get; set; }
public string makerPnl { get; set; }
public string takerPnl { get; set; }
public OZPositions makerPositions { get; set; }
public OZPositions takerPositions { get; set; }
}
Do you have any ideas how I can convert the node "data" to list of "ExPositions" objects, eg. List
I've did this but so far it throws an error
var positions = JsonSerializer.Deserialize<ExPositions>(json_string);
There is an error in your json - it's missing a closing ] for the array (I'll assume it's a typo).
The real problem is that you need a wrapper class to represent the data node of the json which should contain a list (or array) of ExPositions. The makerPositions and takerPositions should also become lists (or arrays) too. Add the following class and update the position properties of ExPositions:
public class Data
{
public List<ExPositions> data { get; set; }
}
// change positions to use a List too
public class ExPositions
{
...
public List<Positions> makerPositions { get; set; }
public List<Positions> takerPositions { get; set; }
}
Then you can deserialize using:
var result = JsonSerializer.Deserialize<Data>(json);
It's not clear where the ""total"": 2 property should be in your models (it's not clear in the json because of the issue I mentioned), you could add it to the Data class above (if it belongs there).
Online demo
Try with:
public class Positions
{
public string name { get; set; }
public string position { get; set; }
public string vwap { get; set; }
public string pnl { get; set; }
}
public class ExPositions
{
public string symbol { get; set; }
public string exposure { get; set; }
public string makerExposure { get; set; }
public string takerExposure { get; set; }
public string makerPnl { get; set; }
public string takerPnl { get; set; }
public Positions makerPositions { get; set; }
public Positions takerPositions { get; set; }
}
public class YourResult{
public ExPositions data { get; set; }
public int total { get; set; }
}
And then call:
var positions = JsonSerializer.Deserialize<YourResult>(json_string);
As haldo mentioned, there is a typo in your JSON. To quickly parse and validate your JSON data, you can use any online JSON parsers to validate your JSON data. I usually use the chrome extension JSON Viewer Pro.
Also, in the link that haldo provided to the .NET Fiddle for the demo, there is a trailing comma in JSON data which JSON deserializers might not ignore.
Here is the link to the edited demo that haldo provided.
Edited Demo
Here is the API that i would like to create ,
{
"Result": "PASS",
"Device": [
{
"ID": "01",
"State": "abc",
},
{
"ID": "02"
"State": "efg",
},
]
}
i want to create the API by return to ApiResult model, Here is my controller,
[HttpGet("device")]
public async Task<ActionResult<ApiResult>> Device()
{
return new ApiResult();
}
My Api Result Model
public class ApiResult
{
public string Result { get; set; }
public ApiDevice[] Device { get; set; }
}
Another model,
public class ApiDevice
{
public string ID { get; set; }
public string State { get; set; }
}
The result that i get is like this,
{"result":null,"device":null}
How to get the result that i need like i mention in first paragraph?
In your example, when you return the new ApiResult from the controller, you are not initializing the properties Result or Device first. You will need to set both of those properties to the appropriate value before returning the object.
Since you are using an array in ApiResult object, you should probably require that values be passed in via the constructor to avoid resizing or replacing the array.
public class ApiResult
{
public string Result { get; set; }
public ApiDevice[] Device { get; set; }
public ApiResult(string result, ApiDevice[] devices) {
Result = result;
Device = devices;
}
}
Another option, which would get you the same JSON data from the API, is to use a List on the ApiResult object.
public class ApiResult
{
public string Result { get; set; }
public List<ApiDevice> Device { get; set; }
public ApiResult() {
Device = new List<ApiDevice>();
}
}
My personal preference would be for the second option.
Your json is invalid, it should be:
{
"Result": "PASS",
"Device": [
{
"ID": "01",
"State": "abc"
},
{
"ID": "02",
"State": "efg"
}
]
}
Your class should be something like:
public class Device
{
public string ID { get; set; }
public string State { get; set; }
}
public class RootObject
{
public string ApiResult { get; set; }
public List<Device> Device { get; set; }
}
This site is great for transposing json to C#: http://json2csharp.com/
I deserialaize my json to a model class fine but i want to do some work on the boxes array before saving to sqlite, I'm stuck on looping through all the boxes and get the values.
{
"data": [ // single outer array
{
"id": 8620379,
"business_id": 191,
"business_name": "yada",
"boxes": [
{
"box_id": 485,
"box_name": "5/6",
"box_group": null
},
{
"box_id": 483,
"box_name": "1/2",
"box_group": null
},
{
"box_id": 484,
"box_name": "3/4",
"box_group": null
}
]
},
{
"id": 8636759,
"business_id": 257,
"business_name": "something else",
"boxes": [
{
"box_id": 1176,
"box_name": "FC",
"box_group": null
}
]
}, // and more boxes
Create a model for the JSON object. (http://json2csharp.com/)
public class Box
{
public int box_id { get; set; }
public string box_name { get; set; }
public object box_group { get; set; }
}
public class Datum
{
public int id { get; set; }
public int business_id { get; set; }
public string business_name { get; set; }
public List<Box> boxes { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
Using Json.NET JSON deserializer,
RootObject obj = JsonConvert.DeserializeObject<RootObject>("your json string");
I have the following Json below coming from a Rest service and I am trying to deserialize it into a C# object using this code:
var _deserializer = new JsonDeserializer();
var results = _deserializer.Deserialize<Report>(restResponse);
The deserialize method keeps returning null which tells me that my C# object is not structured correctly.
Below is the Json and my latest attempt at the C# definition.
{
"Report": [
{
"ID": "0000014",
"Age": "45",
"Details": [
{
"Status": "Approved",
"Name": "Joe"
},
{
"Status": "Approved",
"Name": "Bill"
},
{
"Status": "Submitted",
"Name": "Scott"
}
]
},
{
"ID": "10190476",
"Age": "40",
"Details": [
{
"Status": "Approved",
"Name": "Scott"
}
]
},
{
"ID": "10217480",
"Age": "40",
"Details": [
{
"Status": "Approved",
"Name": "Scott"
}
]
}
]
}
Here is my C# object:
public class Report
{
public List<WorkItem> Item= new List<WorkItem>();
}
public class WorkItem
{
public string ID { get; set; }
public int Age { get; set; }
public List<Details> Details { get; set; }
}
public class Details
{
public string Status { get; set; }
public string Name { get; set; }
}
Can someone advise what is wrong with my C# object definition to make this json deserialize correctly?
I would recommend using Json2Csharp.com to generate the classes.
public class Detail
{
public string Status { get; set; }
public string Name { get; set; }
}
public class Report
{
public string ID { get; set; }
public string Age { get; set; }
public List<Detail> Details { get; set; }
}
public class RootObject
{
public List<Report> Report { get; set; }
}
Try changing the Report class like so (The class name can be anything, the property must be Report)
public class WorkReport
{
public List<WorkItem> Report;
}
It should be trying to deserialize at the root into a class with an array/list of of workitem objects called Report.
You can try something like this. I have changed List to Dictionary You don't have a class defined at the root level. The class structure needs to match the entire JSON, you can't just deserialize from the middle. Whenever you have an object whose keys can change, you need to use a Dictionary. A regular class won't work for that; neither will a List.
public class RootObject
{
[JsonProperty("Report")]
public Report Reports { get; set; }
}
public class Report
{
[JsonProperty("Report")]
public Dictionary<WorkItem> Item;
}
public class WorkItem
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("Age")]
public int Age { get; set; }
[JsonProperty("Details")]
public Dictionary<Details> Details { get; set; }
}
public class Details
{
[JsonProperty("Status")]
public string Status { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
}
Then, deserialize like this:
Report results = _deserializer.Deserialize<Report>(restResponse);
i'm trying to program a Windows Runtime Component in C# in Visual Studio 2012 for Windows 8.
I have some issues by using Json.NET to deserialize a JSON like this:
{
"header": {
"id": 0,
"code": 0,
"hits": 10
},
"body": {
"datalist": [
{
"name": "",
"city": "",
"age": 0
},
{
"name": "",
"city": "",
"age": 0
},
{
"name": "",
"city": "",
"age": 0
}
]
}
}
My intention is to get a top-level Dictionary out of this and to interpret every value as a string. For this example you would get a dictionary with two keys (header and body) and the matching values as strings. After this you could go down the tree.
A function like this
Dictionary<string, string> jsonDict =
JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
would be nice, but this one only accept string-values.
Do anybody knows how to ignore the types or get it on another way?
Furthermore to get out of the body-value "{"datalist": [ { "name": "", ....}]}" a list of dictionaries.
Thanks in advance!
I would use this site and deserialize as
var myObj =JsonConvert.DeserializeObject<RootObject>(json);
public class Header
{
public int id { get; set; }
public int code { get; set; }
public int hits { get; set; }
}
public class Datalist
{
public string name { get; set; }
public string city { get; set; }
public int age { get; set; }
}
public class Body
{
public List<Datalist> datalist { get; set; }
}
public class RootObject
{
public Header header { get; set; }
public Body body { get; set; }
}
You can also use dynamic keyword without declaring any classes
dynamic myObj =JsonConvert.DeserializeObject(json);
var age = myObj.body.datalist[1].age;
And since JObject implements IDictionary<> this is also possible
var jsonDict = JObject.Parse(json);
var age = jsonDict["body"]["datalist"][1]["age"];
If you're having a problem defining your classes, a nice feature in VS 2012 allows you to generate classes to hold your JSON/XML data using the Paste Special command under Edit. For instance, your JSON created this class:
public class Rootobject
{
public Header header { get; set; }
public Body body { get; set; }
}
public class Header
{
public int id { get; set; }
public int code { get; set; }
public int hits { get; set; }
}
public class Body
{
public Datalist[] datalist { get; set; }
}
public class Datalist
{
public string name { get; set; }
public string city { get; set; }
public int age { get; set; }
}
...which you could then deserialize your request into the type of RootObject, e.g.
var obj = JsonConvert.DeserializeObject<RootObject>(json);