deserializing child data collections into ienumerables using JSON.NET - c#

Current I have a project where I'm getting the following sample data ( I want to retrieve only the ids within this json string and stuff them into IEnumerables (explained below):
{
"states": [
{
"id": "AL",
"text": "Alabama (AL)"
},
{
"id": "CO",
"text": "Colorado (CO)"
}
],
"cities": [
{
"id": 71761,
"text": "New Brockton, AL"
},
{
"id": 74988,
"text": "Nathrop, CO"
}
],
"zipCodes": []
}
Notice in the zipCodes, I am getting an empty set, so there is no "id" or "text".
I want to be able to create several IEnumerables from the properties found in this JSON string.
I created an object called Locations that looks like this:
public class Location
{
public IEnumerable<string> States { get; set; }
public IEnumerable<string> ZipCodes { get; set; }
public IEnumerable<decimal> Cities { get; set; }
}
The best way I found to going about this approach is to do each data property one by one and convert, formValues is the json string:
JArray arrStates = (JArray)formValues["states"];
JArray arrCities = (JArray)formValues["cities"];
JArray arrZip = (JArray)formValues["zipCodes"];
and then set the properties in the location object as so:
Location loc = new Location();
loc.States = arrStates.Children().Select(m=>m["id"].Value<string>());
loc.ZipCodes = arrCities.Children().Select(m=>m["id"].Value<string>());
loc.Cities = arrZip.Children().Select(m=>m["id"].Value<string>());
I was wondering if there's a better way of doing this instead of doing all this code maintenance for whenever my json response adds a new property. In fact, I think there's going to be about ten more properties added to the json string.
I want it to be reduced down to where I could just update the Location object, and have the json automatically map to the properties that way. Or atleast a solution that has less maintenance than what I'm doing now.
Also I was wondering if JsonConvert.DeserializeObject would work in my case; but read that JSON.NET treats an IEnumerable as an array, so I'm stumped on this one.

JsonConvert.DeserializeObject would work in your case and it will have less maintenance than what you're doing now.
If you enter your json data to http://json2csharp.com, below is the generated class definition that you can use, I renamed RootObject to Location
public class State
{
public string id { get; set; }
public string text { get; set; }
}
public class City
{
public int id { get; set; }
public string text { get; set; }
}
public class Location
{
public List<State> states { get; set; }
public List<City> cities { get; set; }
public List<object> zipCodes { get; set; }
}
This is how you deserialize the json data into Location
string jsonData = ...; // set the json data here
var location = JsonConvert.DeserializeObject<Location>(jsonData);
You can enumerate through the nested properties to get the ids, for example location.states[0].id will return "AL" and location.cities[1].id will return 74988.
If there's a new property in the json data, let's say it's named countries with id and text like in states, you can create a new Country class
public class Country
{
public string id { get; set; }
public string text { get; set; }
}
and add countries property to Location class
public class Location
{
public List<State> states { get; set; }
public List<City> cities { get; set; }
public List<object> zipCodes { get; set; }
public List<Country> countries { get; set; }
}

Related

Saving JSON to DataTable

I need to save data retrieved from API to a DataTable. JSON which is returned from API can't be deserialized directly to DataTable using this code:
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
I got an error: Unexpected JSON token when reading DataTable. I read that it's beacuse JSON format is not as it should be. Mine is as follows:
{
"page": 1,
"page_size": 1000,
"items": [
{
"id": "e1b019b9a8bf408c9cb964c29e845104",
"asset_id": "5adb0d87882b4e14b99bde74a967e84c",
"alias": "Concrete Pump Yellow",
"serial_number": "QEQ000123",
"model": {
"name": "Pump C50-HP"
},
"operating_hours": {
"hours": 100,
"unit_driven": true
}
}
]
}
I know I need format like [{..}] but can't find workaround, API returns JSON as above. I can deserialize it using this:
var obj = JsonConvert.DeserializeObject(json);
but how can I now add data to DataTable? I'm looking for a solution for it
What the JsonConvert class does is it materializes your string version of the response into an object. For this to work, your string version has to match the structure of the resulting object or the class needs hints to know how to inflate the object. The runtime is telling you that there is a mismatch and it doesn't know how to resolve it.
There are a few ways to get this done. I prefer an structured approach so I would recommend you create classes to receive the data:
var payload = #"{
""page"": 1,
""page_size"": 1000,
""items"": [
{
""id"": ""e1b019b9a8bf408c9cb964c29e845104"",
""asset_id"": ""5adb0d87882b4e14b99bde74a967e84c"",
""alias"": ""Concrete Pump Yellow"",
""serial_number"": ""QEQ000123"",
""model"": {
""name"": ""Pump C50-HP""
},
""operating_hours"": {
""hours"": 100,
""unit_driven"": true
}
}
]
}";
public class ApiResponse
{
[JsonProperty("page")]
public int Page { get; set; }
[JsonProperty("page_size")]
public int PageSize { get; set; }
[JsonProperty("items")]
public IEnumerable<ApiResponseItem> Items { get; set; }
}
public class ApiResponseItem
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("asset_id")]
public string AssetId { get; set; }
[JsonProperty("alias")]
public string Alias { get; set; }
[JsonProperty("serial_number")]
public string SerialNumber { get; set; }
[JsonProperty("model")]
public ApiResponseModel Model { get; set; }
[JsonProperty("operating_hours")]
public ApiResponseOperatingHours OperatingHours { get; set; }
}
public class ApiResponseModel
{
[JsonProperty("name")]
public string Name { get; set; }
}
public class ApiResponseOperatingHours
{
[JsonProperty("hours")]
public string Hours { get; set; }
[JsonProperty("unit_driven")]
public bool UnitDriven { get; set; }
}
var response = JsonConvert.DeserializeObject<ApiResponse>(payload);
As you can see, the classes use hint attributes to let the deserializer know about the fields. You can then loop through the response.Items enumerable and consume the items as desired.
UPDATE:
For posterity and at the suggestion of #mason, it's important to point out that there is no need to use a DataTable. A quick inspection of the payload reveals the output is a paged version of set of records so it's not equivalent to a data table.
Your issue here is that the json you're deserializing is not a DataTable, its just an Object.
JsonConvert.DeserializeObject(request, typeof(Object)) -> Where Object would be a defined Class with parameter definitions to deserialize the json to, i.e page, page_size, id etc..
Once in this format its fairly easy to coerce it into a DataTable:
https://learn.microsoft.com/en-us/dotnet/api/system.data.datatable?view=net-6.0
The Classes would look something along the lines of:
public class Items
{
public Guid? Id {get;set;}
public Guid? AssetId {get;set;}
public string alias {get;set;}
public string serial_number {get;set;}
public Model model {get;set;}
public OperatingHours operatingHours {get;set;}
}
public class Model
{
public string Name { get;set;}
}
public class OperatingHours
{
public int Hours {get;set;}
public bool Unit_Driven {get;set;}
}
public class OverallObject
{
public int Page {get;set;}
public int PageSize {get;set;}
public List<Items> AllItems {get;set;}
}

C# deserialize multiple JSON collections into a single List<T>

I fetch a collection of collections of the same object from a web api.
I would then like to deserialize the JSON into a single List
The JSON is as follows:
{
"Liverpool": [
{
"playerId": "LIV01",
"name": "Adam Llana",
"position": "Midfielder"
},
{
"playerId": "LIV02",
"name": "Daniel Sturridge",
"position": "Forward"
}
],
"ManchesterUnited": [
{
"playerId": "MNU01",
"name": "Daley Blind",
"position": "Defender"
},
{
"playerId": "MNU02",
"name": "Romelu Lukaku",
"position": "Forward"
}
],
"Arsenal": [
{
"playerId": "ARS01",
"name": "Petr Cech",
"position": "Goalkeeper"
},
{
"playerId": "ARS02",
"name": "Santi Cazorla",
"position": "Midfielder"
}
]
}
What I could like to be able to do is the following as I am not interested in the collection names:
public class Player
{
public string playerId { get; set; }
public string name { get; set; }
public string position { get; set; }
}
List<Player> cards = JsonConvert.DeserializeObject<List<Player>>(jsonContent);
This does not work and produces an error.
Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"})
into type 'System.Collections.Generic.List`1[Player]' 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) 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.
Is there any way to accomplish this using Newtonsoft.Json?
Because of the variable team names you need to deserialize into Dictionary<string, List<Player>>. From there use SelectMany on the values of the dictionary to get the players
public class Player
{
public string playerId { get; set; }
public string name { get; set; }
public string position { get; set; }
}
var teams = JsonConvert.DeserializeObject<Dictionary<string, List<Player>>>(jsonContent);
List<Player> players = teams.SelectMany(kvp => kvp.Value).ToList();
What you want is to deserialize that object as a dictionary:
var teams = JsonConvert.DeserializeObject<Dictionary<string, List<Player>>>(jsonContent);
The original object isn't an array so it doesn't make sense to deserialize it as an array or a List<T>
Later, if you want only the player list and don't care about the club names, then just use LINQ's SelectMany to flatten the dictionary:
var allPlayers = teams.SelectMany(entry => entry.Value);
If you simply try to create an object for players right now it won't work as the team names are unique. Your class to deserialize should look like this:
public class Teams
{
public Liverpool[] Liverpool { get; set; }
public Manchesterunited[] ManchesterUnited { get; set; }
public Arsenal[] Arsenal { get; set; }
}
public class Liverpool
{
public string playerId { get; set; }
public string name { get; set; }
public string position { get; set; }
}
public class Manchesterunited
{
public string playerId { get; set; }
public string name { get; set; }
public string position { get; set; }
}
public class Arsenal
{
public string playerId { get; set; }
public string name { get; set; }
public string position { get; set; }
}
Now you can straight away deserialize the data to this object.
Teams teams = JsonConvert.DeserializeObject<Teams>(jsonContent);
Their is an option know as Paste Special inside the Edit option in the top File Menu, this option lets you create classes that mimics the properties of a json or xml.

C# Newtonsoft deserialize JSON array

I'm trying to deserialize an array using Newtonsoft so i can display files from a cloud based server in a listbox but i always end up getting this error no matter what i try:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: [. Path '[0].priv', line 4, position 15.'
Thisis an example try to deserialize:
[
{
"code": 200,
"priv": [
{
"file": "file.txt",
"ext": "txt",
"size": "104.86"
},
{
"file": "file2.exe",
"ext": "exe",
"size": "173.74"
},
],
"pub": [
{
"file": "file.txt",
"ext": "txt",
"size": "104.86"
},
{
"file": "file2.exe",
"ext": "exe",
"size": "173.74"
}
]
}
]
I tried using a C# Class like this:
public class ListJson
{
[JsonProperty("pub")]
public List List { get; set; }
}
public class List
{
[JsonProperty("file")]
public string File { get; set; }
[JsonProperty("ext")]
public string Ext { get; set; }
[JsonProperty("size")]
public string Size { get; set; }
}
[JsonProperty("priv")]
public List List { get; set; }
}
public class List
{
[JsonProperty("file")]
public string File { get; set; }
[JsonProperty("ext")]
public string Ext { get; set; }
[JsonProperty("size")]
public string Size { get; set; }
}
And deserialize with:
List<list> fetch = Newtonsoft.Json.JsonConvert.DeserializeObject<List<list>>(json);
The correct C# class structure for your JSON is the following:
public class FileEntry
{
public string file { get; set; }
public string ext { get; set; }
public string size { get; set; }
}
public class FileList
{
public int code { get; set; }
public List<FileEntry> priv { get; set; }
public List<FileEntry> pub { get; set; }
}
Deserializing it in this way:
var fetch = JsonConvert.DeserializeObject<FileList[]>(json);
var fileList = fetch.First(); // here we have a single FileList object
As said in the other answer, creating a class called List doesn't automagically turn it into a collection of objects. You need to declare the types to be deserialized from an array a collection type (e.g. List<T>, T[], etc.).
Small tip: when in doubt, use json2csharp.com to generate strongly typed classes from a json string.
At the moment List has a single List instance called priv, which despite the name: doesn't make it a list. To deserialize a JSON array ("priv": [...]), it needs to an array or list-like type, for example List<T> for some T. Presumably a List<FileThing>, if we assume that FileThing is actually the second type called List (you have 2).

Runtime Binder Exception

After a deserialization I save the content in an object:
var obj = JsonConvert.DeserializeObject<dynamic>(responseText);
so I execute a loop for populate a DataGrid
foreach(var item in obj)
{
MainWindow.AppWindow.Squadre_DataGrid.Items.Add(new Teams.Club_Information
{
code = item.code,
name = item.name,
shortName = item.shortName,
squadMarketValue = item.squadMarketValue
});
}
The problem's that inside the foreach the compiler show Runtime Binder Exception.
Why happean this?
Some more details:
Class structure
public class Self
{
public string href { get; set; }
}
public class Fixtures
{
public string href { get; set; }
}
public class Players
{
public string href { get; set; }
}
public class Links
{
public Self self { get; set; }
public Fixtures fixtures { get; set; }
public Players players { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public string name { get; set; }
public string code { get; set; }
public string shortName { get; set; }
public string squadMarketValue { get; set; }
public string crestUrl { get; set; }
}
JSON structure:
{
"_links": {
"self": { "href": "http://api.football-data.org/alpha/teams/19" },
"fixtures": { "href": "http://api.football-data.org/alpha/teams/19/fixtures" },
"players": { "href": "http://api.football-data.org/alpha/teams/19/players" }
},
"name": "Eintracht Frankfurt",
"code": "SGE",
"shortName": "Eintr. Frankfurt",
"squadMarketValue": "75.475.000 ?",
"crestUrl": "http://upload.wikimedia.org/wikipedia/commons/0/04/Eintracht_Frankfurt_Logo.svg"
}
The object you are deserializing does not contain a property named code. So the line code = item.code causes an exception at runtime, because the Json.Net object behind the dynamic does not contain a value named code.
This means that the Json that you are parsing does not contain a property named code. Or else it only sometimes contains a property named code. In that case you'll have to either parse it is a JObject and check if the property exists or create an type do deserialize it into.'
Edit
Based on the Json that you posted along with the class structure it looks like you should just be deserializing directly into a RootObject class:
var obj = JsonConvert.DeserializeObject<RootObject>(responseText);
Or in any case you can still deserialize into a dynamic but you need to get rid of the foreach since you don't have a collection of RootObject
var obj = JsonConvert.DeserializeObject<dynamic>(responseText);
MainWindow.AppWindow.Squadre_DataGrid.Items.Add(new Teams.Club_Information
{
code = obj.code,
name = obj.name,
shortName = obj.shortName,
squadMarketValue = obj.squadMarketValue
});
Where you went wrong was the foreach. Since obj is dynamic there is no compiler error and the Json.Net JObject that is returned supports iteraction. But the that gives you back each of the property values, (e.g. _links, name, etc) on at a time, not the object that you are interested in.

nested json c# object deserialization

i have the following json string (jsonString)
[
{
"name":"Fruits",
"references":[
{"stream":{"type":"reference","size":"original",id":"1"}},
],
"arts":[
{"stream":{"type":"art","size":"original","id":"4"}},
{"stream":{"type":"art","size":"medium","id":"9"}},
]
}
]
and the following C# objects
class Item
{
public string Name { get; set; }
public List<Stream> References { get; set; }
public List<Stream> Arts { get; set; }
public Item()
{
}
}
class Stream
{
public string Type { get; set; }
public string Size { get; set; }
public string Id { get; set; }
public Stream()
{
}
}
and the following code
Item item = JsonConvert.DeserializeObject<Item>(jsonString);
when I run the code, it creteas the correct number of references and arts, but each stream has null value (type = null, size = null).
is it posible to do this json.net deserializeobject method or should I manually deserialize ?
EDIT: Okay, ignore the previous answer. The problem is that your arrays (references and arts) contain objects which in turn contain the relevant data. Basically you've got one layer of wrapping too many. For example, this JSON works fine:
[
{
"name":"Fruits",
"references":[
{"Type":"reference","Size":"original","Id":"1"},
],
"arts":[
{"Type":"art","Size":"original","id":"4"},
{"type":"art","size":"medium","id":"9"},
]
}
]
If you can't change the JSON, you may need to introduce a new wrapper type into your object model:
public class StreamWrapper
{
public Stream Stream { get; set; }
}
Then make your Item class have List<StreamWrapper> variables instead of List<Stream>. Does that help?

Categories

Resources