Deserialize json to c# - c#

How should my C# sharp object look like, I would like to deserialize the following JSON string to a C# object.
{
"PersonId": "XXXXXXXXXXXXXX",
"Name": "XXXXXXXX",
"HobbiesCollection":
{"Hobby":
[
{
"type": "RUNNING",
"id": 44,
"description": "sprinting and sprinting?"
},
{
"type": "RUNNING",
"id": 45,
"description": "jogging and jogging"
}
]
}
}

Here is what is generated in VS2013
public class Rootobject
{
public string PersonId { get; set; }
public string Name { get; set; }
public Hobbiescollection HobbiesCollection { get; set; }
}
public class Hobbiescollection
{
public Hobby[] Hobby { get; set; }
}
public class Hobby
{
public string type { get; set; }
public int id { get; set; }
public string description { get; set; }
}
You can use VS2012/2013 feature Edit/Paste Special/Paste JSON As Classes to simplify this process.

There is a online tool you can make C# class from your String
JSON to Csharp
public class Hobby
{
public string type { get; set; }
public int id { get; set; }
public string description { get; set; }
}
public class HobbiesCollection
{
public List<Hobby> Hobby { get; set; }
}
public class RootObject
{
public string PersonId { get; set; }
public string Name { get; set; }
public HobbiesCollection HobbiesCollection { get; set; }
}

Related

How can I deserialise a complex and nested JSON?

In my c# project, I would like to access specific information (POI name and distance) inside a complex and nested JSON.
This JSON is the result of an Azure Maps API call.
I have tried to deserialise it into an object. But this JSON is too complex and I am unable to do it.
What is the best way to extract the information I need ?
{
"summary": {
"query": "university",
"queryType": "NON_NEAR",
"queryTime": 103,
"numResults": 1,
"offset": 0,
"totalResults": 216684,
"fuzzyLevel": 1,
"geoBias": {
"lat": 48.008446,
"lon": 7.821583
}
},
"results": [
{
"type": "POI",
"id": "DE/POI/p0/1505647",
"score": 2.574,
"dist": 774.6544330765787,
"info": "search:ta:276009006412786-DE",
"poi": {
"name": "Universität Freiburg Medizinische Fakultät",
"phone": "+(49)-(761)-27072350",
"url": "www.med.uni-freiburg.de",
"categories": [
"college/university"
],
"classifications": [
{
"code": "COLLEGE_UNIVERSITY",
"names": [
{
"nameLocale": "en-US",
"name": "college/university"
}
]
}
]
},
"address": {
"streetName": "Elsässer Straße",
"municipalitySubdivision": "Mooswald",
"municipality": "Freiburg im Breisgau",
"countrySecondarySubdivision": "Freiburg im Breisgau",
"countrySubdivision": "Baden-Württemberg",
"postalCode": "79110",
"countryCode": "DE",
"country": "Germany",
"countryCodeISO3": "DEU",
"freeformAddress": "Elsässer Straße, 79110 Freiburg Im Breisgau"
},
"position": {
"lat": 48.00894,
"lon": 7.83197
},
"viewport": {
"topLeftPoint": {
"lat": 48.00984,
"lon": 7.83063
},
"btmRightPoint": {
"lat": 48.00804,
"lon": 7.83331
}
},
"entryPoints": [
{
"type": "main",
"position": {
"lat": 48.00931,
"lon": 7.83259
}
}
]
}
]
}
Step 1:
Parse your JSON in a JSON parser website such as https://jsonparser.org
This will help you understand the content and how it will be translated as an object.
For example, your JSON string gives this result :
Step2:
Open the query tool of this website, this will help you find out the object path to the information you need.
For example, for your JSON string, to access the POI name :
Step 3:
In your Visual Studio project, install the NuGet package: Newtonsoft.Json and Microsoft.CSharp in your shared library.
If you are processing the JSON in a separate library, please also install the Newtonsoft.Json NuGet package in the main project.
Step 4:
If JSONstring is your JSON string :
using Newtonsoft.Json;
dynamic NewObject = JsonConvert.DeserializeObject<dynamic>(JSONstring);
string Name = NewObject.results[0].poi.name;
string Distance = NewObject.results[0].dist;
You have at least 2 solutions possible:
Either you create classes that mirror the content of the json you are expecting
public class MyJSON
{
public Summary summary { get; set; }
public List<Result> results { get; set; }
...
}
public class Summary
{
public string query { get; set; }
...
}
Then you could deserialize using Newtonsoft.Json
JsonConvert.DeserializeObject<MyJSON>(jsonstring);
Or you could directly deserialize to a dynamic object and access the properties directly by name.
dynamic data = JsonConvert.DeserializeObject<dynamic>(jsonstring);
string query = data[0].summary.query;
Solution 1 requires you to create the classes first, but is faster and more secure to access (less prone to wrong naming, or data structure changes)
Solution 2 is much more volatile and flexible, you just access what you need. But you could get exceptions if you try to access properties that do not exist in the json object.
i converted your json via json2csharp
then you can use Newtonsoft to deserialize them
RootObject root= JsonConvert.DeserializeObject(JSONstring)
public class GeoBias
{
public double lat { get; set; }
public double lon { get; set; }
}
public class Summary
{
public string query { get; set; }
public string queryType { get; set; }
public int queryTime { get; set; }
public int numResults { get; set; }
public int offset { get; set; }
public int totalResults { get; set; }
public int fuzzyLevel { get; set; }
public GeoBias geoBias { get; set; }
}
public class Name
{
public string nameLocale { get; set; }
public string name { get; set; }
}
public class Classification
{
public string code { get; set; }
public List<Name> names { get; set; }
}
public class Poi
{
public string name { get; set; }
public string phone { get; set; }
public string url { get; set; }
public List<string> categories { get; set; }
public List<Classification> classifications { get; set; }
}
public class Address
{
public string streetName { get; set; }
public string municipalitySubdivision { get; set; }
public string municipality { get; set; }
public string countrySecondarySubdivision { get; set; }
public string countrySubdivision { get; set; }
public string postalCode { get; set; }
public string countryCode { get; set; }
public string country { get; set; }
public string countryCodeISO3 { get; set; }
public string freeformAddress { get; set; }
}
public class Position
{
public double lat { get; set; }
public double lon { get; set; }
}
public class TopLeftPoint
{
public double lat { get; set; }
public double lon { get; set; }
}
public class BtmRightPoint
{
public double lat { get; set; }
public double lon { get; set; }
}
public class Viewport
{
public TopLeftPoint topLeftPoint { get; set; }
public BtmRightPoint btmRightPoint { get; set; }
}
public class Position2
{
public double lat { get; set; }
public double lon { get; set; }
}
public class EntryPoint
{
public string type { get; set; }
public Position2 position { get; set; }
}
public class Result
{
public string type { get; set; }
public string id { get; set; }
public double score { get; set; }
public double dist { get; set; }
public string info { get; set; }
public Poi poi { get; set; }
public Address address { get; set; }
public Position position { get; set; }
public Viewport viewport { get; set; }
public List<EntryPoint> entryPoints { get; set; }
}
public class RootObject
{
public Summary summary { get; set; }
public List<Result> results { get; set; }
}

Parsing JSON with LINQ into List of Objects

I'm a little confused on the best way to parse the following JSON structure.
{
"featured": {
"id": 15,
"title": "media 1 -> 7",
"description": "test1",
"short_description": "test1",
"rating_avg": 0.0,
"image": "//d25xdrj7gd7wz1.cloudfront.net/covers/1603/1452024324.jpg"
},
"categories": [
{
"id": 1,
"title": "category 0",
"description": null,
"position": 0,
"media": [
{
"id": 1,
"title": "media 0 -> 0",
"description": "test1",
"short_description": "test1",
"rating_avg": 0.0,
"image": "//d25xdrj7gd7wz1.cloudfront.net/covers/1603/1452024324.jpg",
"category_media": {
"position": 0,
"category_id": 1,
"media_id": 1,
"id": 1
}
}, ...
Basically I have an array of categories which contains an array of medias (the featured is for something else)
I am looking to return List and the Category object contains a List
and I created some models:
public class Category
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public List<Media> MediaList { get; set; }
}
public class Media
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string ShortDescription { get; set; }
public string Image { get; set; }
}
..and I am supposed to use Newtonsoft?
I looked at the following example: Deserializing Partial JSON Fragments but I would think I don't need to convert from JToken -> Category ... etc. In other words, I would think it would be easy to just return my List.
I'm new to LINQ (I come from a python background) so I'm getting to know C#
Use This as your Model
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class JsonModel
{
[JsonProperty("featured")]
public Featured Featured { get; set; }
[JsonProperty("categories")]
public List<Category> Categories { get; set; }
}
public partial class Category
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public object Description { get; set; }
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("media")]
public List<Featured> Media { get; set; }
}
public partial class Featured
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("short_description")]
public string ShortDescription { get; set; }
[JsonProperty("rating_avg")]
public long RatingAvg { get; set; }
[JsonProperty("image")]
public string Image { get; set; }
[JsonProperty("category_media", NullValueHandling = NullValueHandling.Ignore)]
public CategoryMedia CategoryMedia { get; set; }
}
public partial class CategoryMedia
{
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("category_id")]
public long CategoryId { get; set; }
[JsonProperty("media_id")]
public long MediaId { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
}
}
Then do this in your Class:
var info = JsonConvert.DeserializeObject<JsonModel>(json);
var featured = info.Featured;
var categories = info.Categories;
You don't need LINQ in this case unless you want to change the data structure. To parse json file to list you have to create a class that matches a structure of your file, like:
class DataModel
{
public Featured Featured { get; set; }
public List<Category> Categories { get;set; }
}
Also, please pay attention that you need to use attribute [JsonProperty(PropertyName="fieldName")] if property name in json is different from property name in class.
And finally, to parse the data use the following row:
var data = JsonConvert.DeserializeObject<DataModel>(jsonString);
Act as follow:
Update your models with:
public class Category
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public List<Media> Media { get; set; }
}
public class Media
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string ShortDescription { get; set; }
public string Image { get; set; }
}
public class Featured
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Short_Description { get; set; }
}
And then make a model same as your JSON structure:
public class YOUR_MODEL
{
public Featured Featured { get; set; }
public List<Category> Categories { get;set; }
}
And then Descrilize your JSON to your object:
YOUR_MODELresults = JsonConvert.DeserializeObject<YOUR_MODEL>(YOUR_JSON);
To get your model you can use tool like :
https://jsonutils.com/ or http://json2csharp.com/
In case of need you can also validate json syntax with : https://jsonlint.com/ to get detailed errors.
With a slightly modified version of your example, I get :
public class CategoryMedia
{
public int position { get; set; }
public int category_id { get; set; }
public int media_id { get; set; }
public int id { get; set; }
}
public class Medium
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string short_description { get; set; }
public double rating_avg { get; set; }
public string image { get; set; }
public CategoryMedia category_media { get; set; }
}
public class Category
{
public int id { get; set; }
public string title { get; set; }
public object description { get; set; }
public int position { get; set; }
public IList<Medium> media { get; set; }
}
public class Featured
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string short_description { get; set; }
public double rating_avg { get; set; }
public string image { get; set; }
public IList<Category> categories { get; set; }
}
public class Example
{
public Featured featured { get; set; }
}
It spares a lot of time for creating models and it allows you to verify that you don't have typos in field names.
With this, you just have to deserialize your JSON sample to "Example" class, using the library of your choice. Newtonsoft Json is a very efficient classical !
Newtonsoft is the standard for doing work like this. So lets look at the best way to do this. First lets start with your json format and fix it so you can use the online tools available to create a good model structure:
[
{
"featured": {
"id": 15,
"title": "media 1 -> 7",
"description": "test1",
"short_description": "test1",
"rating_avg": 0.0,
"image": "//d25xdrj7gd7wz1.cloudfront.net/covers/1603/1452024324.jpg"
},
"categories": [
{
"id": 1,
"title": "category 0",
"description": null,
"position": 0,
"media": [
{
"id": 1,
"title": "media 0 -> 0",
"description": "test1",
"short_description": "test1",
"rating_avg": 0.0,
"image": "//d25xdrj7gd7wz1.cloudfront.net/covers/1603/1452024324.jpg",
"category_media": {
"position": 0,
"category_id": 1,
"media_id": 1,
"id": 1
}
}
]
}
]
}
]
Now if you plug that into http://json2csharp.com/, it will output a good model structure:
public class Featured
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string short_description { get; set; }
public double rating_avg { get; set; }
public string image { get; set; }
}
public class CategoryMedia
{
public int position { get; set; }
public int category_id { get; set; }
public int media_id { get; set; }
public int id { get; set; }
}
public class Medium
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string short_description { get; set; }
public double rating_avg { get; set; }
public string image { get; set; }
public CategoryMedia category_media { get; set; }
}
public class Category
{
public int id { get; set; }
public string title { get; set; }
public object description { get; set; }
public int position { get; set; }
public List<Medium> media { get; set; }
}
public class RootObject
{
public Featured featured { get; set; }
public List<Category> categories { get; set; }
}
Feel free to rename RootObject So now lets look are how you can deserialize your json into your model objects using Newtonsoft:
Firstly you need to get your json file into a string format, so lets say its a file on your computer or in your project, there is many ways to retrieve it, either using Assembly, or Directory methods. Once you have access to your json file, read out the contents and then using Newtonsoft method for deserialising:
var myString = File.ReadAllText(path)
var myObject = JsonConvert.DeserializeObject<RootObject>(myString);
And thats it:P

Serializing Json to c# Class throwing error

I have a JSON returning from web like this
{
"data": {
"normal_customer": {
"0": {
"id": 1,
"name": "ALPHY"
}
},
"1": {
"id": 2,
"name": "STEVEN"
}
},
"luxury_customer": {
"3": {
"id": 8,
"name": "DEV"
}
}
}
}
I have created c# classes
public class StandardCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
public class LuxuryCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class Data
{
public StandardCustomers standard_Customers { get; set; }
public LuxuryCustomers luxury_Customers { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
}
When I use deserialize the response from the website using below c# code
var result1 = JsonConvert.DeserializeObject<Data>(response);
but result1.luxury_customers contains customerdetails which is null.
As suggested by #hellostone, I have modified to rootdata, then also
result1.luxury_customers contains customerdetails is null.
Any idea how to deserialize to c# class
When we pasted Json to visual studio, it generated classes as below
public class Rootobject
{
public Data data { get; set; }
}
public class Data
{
public Standard_Customers standard_Customers { get; set; }
public Luxury_Customers luxury_Customers { get; set; }
}
public class Standard_Customers
{
public _0 _0 { get; set; }
public _1 _1 { get; set; }
public _2 _2 { get; set; }
public _4 _4 { get; set; }
public _5 _5 { get; set; }
}
public class _0
{
public int id { get; set; }
public string name { get; set; }
}
individual classes are generated in standard customers , can we use list for this
I guess the problem is that index in luxury_customers starting not from zero. Try to use Dictionary<string,CustomersDetails> in LuxuryCustomers instead List<CustomersDetails>.
I've managed to deserialize Json with this classes:
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
}
public class Data
{
public Dictionary<string, CustomersDetails> normal_customer { get; set; }
public Dictionary<string,CustomersDetails> luxury_customer { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
Deserialization code:
var result = JsonConvert.DeserializeObject<RootObject>(text);
P.S. I've remove one closing bracket after "ALPHY" element, to make Json valid, I hope it was typo and you're getting valid Json.
Your json string doesn't match with your defined classes. Your Json string should look like this if you want to preserve your class structure:
{
"data":{
"standard_Customers":{
"Customers_Details":[
{
"id":1,
"name":"ALPHY"
},
{
"id":2,
"name":"STEVEN"
}
]
},
"luxury_Customers":{
"Customers_Details":[
{
"id":8,
"name":"DEV"
}
]
}
}
}
Pay attention to the square brackets at the "Customers_Details" attribute.
Then the:
var result1 = JsonConvert.DeserializeObject<RootObject>(response);
call, will give you the right object back and it shouldn't be null, when using your class structure:
public class StandardCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
}
public class LuxuryCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class Data
{
public StandardCustomers standard_Customers { get; set; }
public LuxuryCustomers luxury_Customers { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}

C# class that would represent JSON data

what would the C# class definition look like to represent this JSON data?
{
"accountId": "101",
"website": "www.example.com",
"alternateWebsites": [
{
"website": "site2.example.com"
}
],
"email": "contact#mysite.com",
"alternateEmails": [
{
"email": "sales#example.com"
}
],
"address": {
"street": "234 Main Street",
"city": "San Diego",
"postalCode": "92101",
"state": "CA"
},
"rankingKeywords":
[{
"keyword": "Coffee",
"localArea": "Sacramento, CA"
}]
}
You can use a site like this http://jsonutils.com/
where you paste in your json and it constructs your classes for you. The result of your JSON produced...
public class AlternateWebsite
{
public string website { get; set; }
}
public class AlternateEmail
{
public string email { get; set; }
}
public class Address
{
public string street { get; set; }
public string city { get; set; }
public string postalCode { get; set; }
public string state { get; set; }
}
public class RankingKeyword
{
public string keyword { get; set; }
public string localArea { get; set; }
}
public class Root
{
public string accountId { get; set; }
public string website { get; set; }
public IList<AlternateWebsite> alternateWebsites { get; set; }
public string email { get; set; }
public IList<AlternateEmail> alternateEmails { get; set; }
public Address address { get; set; }
public IList<RankingKeyword> rankingKeywords { get; set; }
}
You could convert this with a service like http://json2csharp.com/. Enter the JSON and it will spit out C# model classes. Then, add them either as a class, or using Entity Framework (depending on your objective) into your project.
C# version:
public class AlternateWebsite
{
public string website { get; set; }
}
public class AlternateEmail
{
public string email { get; set; }
}
public class Address
{
public string street { get; set; }
public string city { get; set; }
public string postalCode { get; set; }
public string state { get; set; }
}
public class RankingKeyword
{
public string keyword { get; set; }
public string localArea { get; set; }
}
public class RootObject
{
public string accountId { get; set; }
public string website { get; set; }
public List<AlternateWebsite> alternateWebsites { get; set; }
public string email { get; set; }
public List<AlternateEmail> alternateEmails { get; set; }
public Address address { get; set; }
public List<RankingKeyword> rankingKeywords { get; set; }
}

How to Deserialize deeply nested json array in asp.net C#

JSon String is given below:
{
"properties": {
"jci": [
{
"firstName": "Henk",
"lastName": "de Vries",
"Photo": "http://s3.amazonaws.com/mendeley-photos/6a/bd/6abdab776feb7a1fd4e5b4979ea9c5bfc754fd29.png",
"Title": "Dr.",
"Position": "Head of research group",
"Institution": "Vrije Universiteit Amsterdam",
"Fields_of_interest": ["medicine", "computer science"],
"emailAddress": "henk.de.vries#science.com",
"editorship": [
{
"title": "Dr.",
"editorial_role": "Editor in chief",
"date_start": 1460116283,
"date_end": 1460116283,
"publisher": {
"name": "Elsevier",
"role": "Project manager",
"emailAddress": "journal#elsevier.com"
}
}
]
}
],
"sid": [
{
"firstName": "Henk",
"lastName": "de Vries",
"Title": "Dr.",
"primary organisation": "Vrije Universiteit Amsterdam",
"emailAddress": "henk.de.vries#science.com",
"editorship": [
{
"title": "Dr.",
"editorial_role": "Editor in chief",
"publication_year": 2012
}
]
}
]
}
}
I have written code to deserialization
JavaScriptSerializer ser = new JavaScriptSerializer();
JsonTest foo = new JsonTest();
foo = (JsonTest)ser.Deserialize<JsonTest>(JSONString);
public class JsonTest
{
public properties properties { get; set; }
}
public class properties
{
public List<jci> jci { get; set; }
public List<sid>sid { get; set; }
}
public class jci
{
public string firstName { get; set; }
public string lastName { get; set; }
public string Photo { get; set; }
public string Position { get; set; }
public string Institution { get; set; }
public string emailAddress { get; set; }
public string Title { get; set; }
public List<string> Fields_of_interest { get; set; }
public List<editorship> editorship { get; set; }
}
public class editorship
{
public string title { get; set; }
public string editorial_role { get; set; }
public string date_start { get; set; }
public string date_end { get; set; }
public Dictionary<string, string> publisher { get; set; }
}
in this code there are 2 arrays of object called "editorship".. I have created "editorship" class for "jci".. how to access the values of editorship array of sid...?
Using json2csharp i generated these classes based on your JSON
public class Publisher
{
public string name { get; set; }
public string role { get; set; }
public string emailAddress { get; set; }
}
public class Editorship
{
public string title { get; set; }
public string editorial_role { get; set; }
public int date_start { get; set; }
public int date_end { get; set; }
public Publisher publisher { get; set; }
}
public class Jci
{
public string firstName { get; set; }
public string lastName { get; set; }
public string Photo { get; set; }
public string Title { get; set; }
public string Position { get; set; }
public string Institution { get; set; }
public List<string> Fields_of_interest { get; set; }
public string emailAddress { get; set; }
public List<Editorship> editorship { get; set; }
}
public class Editorship2
{
public string title { get; set; }
public string editorial_role { get; set; }
public int publication_year { get; set; }
}
public class Sid
{
public string firstName { get; set; }
public string lastName { get; set; }
public string Title { get; set; }
public string primary_organisation { get; set; }
public string emailAddress { get; set; }
public List<Editorship2> editorship { get; set; }
}
public class Properties
{
public List<Jci> jci { get; set; }
public List<Sid> sid { get; set; }
}
public class RootObject
{
public Properties properties { get; set; }
}
You can then access your editorial values like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var collection = serializer.Deserialize<RootObject>(jsonString);
foreach (var j in collection.properties.sid)
{
Console.Write(j.editorship);
}
On a side note, you should consider using names that are more readable then jci and sid

Categories