Related
I am having a difficulty trying to extract data from the following JSON table:
[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]
}
]
My goal is to get a string output for each "word" and each "definition". I have the following class which corresponds to the JSON file:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string type { get; set; }
public string version { get; set; }
public string comment { get; set; }
public string name { get; set; }
public string database { get; set; }
public Datum[] data { get; set; }
}
public class Datum
{
public string id { get; set; }
public string word { get; set; }
public object synonym { get; set; }
public string definition { get; set; }
}
Finally this piece of code is supposed to retrieve the first word from the table in the string result:
var list = JsonConvert.DeserializeObject<List<Dictionary.Rootobject>>(rawJSON);
string result = list[0].Property1[0].data[0].word;
The .Property[0] returns null and the program gives me a null reference exception. Where is my code faulty and how should I accomplish this task? Thank you.
EDIT:
I am not sure whether this can mess up the rawJSON string but I get it like this:
rawJSON = File.ReadAllText(FileSystem.AppDataDirectory + fileName);
# Claudio Valerio provide the right json data.
Based on my test, you could try the code below to get the word in the list.
Json daya:
{
"Property1":[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]
}
]
}
Class from JSON data:
public class Rootobject
{
public Property1[] Property1 { get; set; }
}
public class Property1
{
public string type { get; set; }
public string version { get; set; }
public string comment { get; set; }
public string name { get; set; }
public string database { get; set; }
public Datum[] data { get; set; }
}
public class Datum
{
public string id { get; set; }
public string word { get; set; }
public object synonym { get; set; }
public string definition { get; set; }
}
Code:
string rawJSON = #"{
'Property1':[
{'type':'header','version':'4.8.3','comment':'Export to JSON plugin for PHPMyAdmin'},
{'type':'database','name':'archaism_dictionary'},
{'type':'table','name':'dictionary','database':'archaism_dictionary','data':
[
{'id':'0','word':'wordOne','synonym':null,'definition':'defOne'},
{'id':'1','word':'wortTwo','synonym':null,'definition':'defTwo'}
]
}
]
}";
var list = JsonConvert.DeserializeObject<Rootobject>(rawJSON);
string result = list.Property1[2].data[0].word;
It is more likely that your input json is something like this:
[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]
Note square brakets, they're important.
If I guessed it right, you'll want to deserialize like this:
var list = JsonConvert.DeserializeObject<List<Class1>>(rawJSON);
string result = list[2].data[0].word;
Note: your original code would work only if your input json were:
{
"Property1":[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]
}
]
}
and use
var myRoot = JsonConvert.DeserializeObject<RootObject>(rawJSON);
string result = myRoot.Property1[2].data[0].word;
You need to null handle(json NullValueHandling) below is my code please take a look :
string stringJson = #"{
'Property1':[
{'type':'header','version':'4.8.3','comment':'Export to JSON plugin for PHPMyAdmin'},
{'type':'database','name':'archaism_dictionary'},
{'type':'table','name':'dictionary','database':'archaism_dictionary','data':
[
{'id':'0','word':'wordOne','synonym':null,'definition':'defOne'},
{'id':'1','word':'wortTwo','synonym':null,'definition':'defTwo'}
]
}
]
}";
try
{
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var list = JsonConvert.DeserializeObject<BaseResponse>(stringJson,settings);
string result = list.Property1[2].data[0].word;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Models :
public class WordData
{
public string id { get; set; }
public string word { get; set; }
public object synonym { get; set; }
public string definition { get; set; }
}
public class PropertyData
{
public string type { get; set; }
public string version { get; set; }
public string comment { get; set; }
public string name { get; set; }
public string database { get; set; }
public List<WordData> data { get; set; }
}
public class BaseResponse
{
public List<PropertyData> Property1 { get; set; }
}
I hope it will help you
Thanks
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; }
}
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
I'm trying to extract some data from json. I've been looking for a solution either in JSS or Json.net but haven't been able to figure this problem out. this is how my Json looks like:
Note: i Have tested and the mapping and decentralization works! I'm looking for a way to extract specifc data from the json!
Thanks in Advance!
{
"tasks":[
{
"id":"tmp_fk1345624806538",
"name":"Gantt editor ",
"code":"",
"level":0,
"status":"STATUS_ACTIVE",
"start":1346623200000,
"duration":5,
"end":1347055199999,
"startIsMilestone":false,
"endIsMilestone":false,
"assigs":[
{
"resourceId":"tmp_3",
"id":"tmp_1345625008213",
"roleId":"tmp_1",
"effort":7200000
}
],
"depends":"",
"description":"",
"progress":0
},
{
"id":"tmp_fk1345624806539",
"name":"phase 1",
"code":"",
"level":1,
"status":"STATUS_ACTIVE",
"start":1346623200000,
"duration":2,
"end":1346795999999,
"startIsMilestone":false,
"endIsMilestone":false,
"assigs":[
{
"resourceId":"tmp_1",
"id":"tmp_1345624980735",
"roleId":"tmp_1",
"effort":36000000
}
],
"depends":"",
"description":"",
"progress":0
},
{
"id":"tmp_fk1345624789530",
"name":"phase 2",
"code":"",
"level":1,
"status":"STATUS_SUSPENDED",
"start":1346796000000,
"duration":3,
"end":1347055199999,
"startIsMilestone":false,
"endIsMilestone":false,
"assigs":[
{
"resourceId":"tmp_2",
"id":"tmp_1345624993405",
"roleId":"tmp_2",
"effort":36000000
}
],
"depends":"2",
"description":"",
"progress":0
}
],
"resources":[
{
"id":"tmp_1",
"name":"Resource 1"
},
{
"id":"tmp_2",
"name":"Resource 2"
},
{
"id":"tmp_3",
"name":"Resource 3"
}
],"roles":[
{
"id":"tmp_1",
"name":"Project Manager"
},
{
"id":"tmp_2",
"name":"Worker"
}
],
"canWrite":true,
"canWriteOnParent":true,
"selectedRow":0,
"deletedTaskIds":[],
}
i've already mapped as follow
public class Rootobject
{
public Task[] tasks { get; set; }
public Resource[] resources { get; set; }
public Role[] roles { get; set; }
public bool canWrite { get; set; }
public bool canWriteOnParent { get; set; }
public int selectedRow { get; set; }
public object[] deletedTaskIds { get; set; }
}
public class Task
{
public string id { get; set; }
public string name { get; set; }
public string code { get; set; }
public int level { get; set; }
public string status { get; set; }
public long start { get; set; }
public int duration { get; set; }
public long end { get; set; }
public bool startIsMilestone { get; set; }
public bool endIsMilestone { get; set; }
public Assig[] assigs { get; set; }
public string depends { get; set; }
public string description { get; set; }
public int progress { get; set; }
}
public class Assig
{
public string resourceId { get; set; }
public string id { get; set; }
public string roleId { get; set; }
public int effort { get; set; }
}
public class Resource
{
public string id { get; set; }
public string name { get; set; }
}
public class Role
{
public string id { get; set; }
public string name { get; set; }
}
and I need to extract following information from my json.(from specific Task in may json! for example the first one with id : tmp_fk1345624806538 ).
Note: i'm getting my json from a json file as follow:
string startDate; // this is what i need to extract
string endDate; // this is what i need to extract
string Progress; // this is what i need to extract
public void load()
{
GC.GClass l = new GC.GClass();
string jsonString = l.load(); // i get my json from a json file
Rootobject project = JsonConvert.DeserializeObject<Rootobject>(jsonString);
}
You can use LINQ to query the object quickly.
Task task = project.tasks.FirstOrDefault(t=> t.id == "tmp_fk1345624806538");
Test task, and if null then there was not task with matching id. If you are sure that there will be a matching task your can just use .First(), but it will throw an exception if there is no match in the list
You'll need to add a using System.Linq; if you don't have that already.
I have an JSON result like this
{
"authenticationResultCode":"ValidCredentials",
"brandLogoUri":"http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png",
"copyright":"Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
"resourceSets":[
{
"estimatedTotal":1,
"resources":[
{
"__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
"bbox":[
47.636257744012461,
-122.13735364288299,
47.643983179153814,
-122.12206713944467
],
"name":"1 Microsoft Way, Redmond, WA 98052",
"point":{
"type":"Point",
"coordinates":[
47.640120461583138,
-122.12971039116383
]
},
"address":{
"addressLine":"1 Microsoft Way",
"adminDistrict":"WA",
"adminDistrict2":"King Co.",
"countryRegion":"United States",
"formattedAddress":"1 Microsoft Way, Redmond, WA 98052",
"locality":"Redmond",
"postalCode":"98052"
},
"confidence":"High",
"entityType":"Address",
"geocodePoints":[
{
"type":"Point",
"coordinates":[
47.640120461583138,
-122.12971039116383
],
"calculationMethod":"InterpolationOffset",
"usageTypes":[
"Display"
]
},
{
"type":"Point",
"coordinates":[
47.640144601464272,
-122.12976671755314
],
"calculationMethod":"Interpolation",
"usageTypes":[
"Route"
]
}
],
"matchCodes":[
"Good"
]
}
]
}
],
"statusCode":200,
"statusDescription":"OK",
"traceId":"b0b1286504404eafa7e7dad3e749d570"
}
I want to get a list of objects, and every object will contain the value of coordinates
So how can access these element by name?
I am using C# as a code behind.
You can use package like Json.NET for this task.
and easily you can generate classes by giving json string from http://json2csharp.com/
then you can access properties of items as below
RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonText);
below are the classes generated from the json2csharp for given json
public class Point
{
public string type { get; set; }
public List<double> coordinates { get; set; }
}
public class Address
{
public string addressLine { get; set; }
public string adminDistrict { get; set; }
public string adminDistrict2 { get; set; }
public string countryRegion { get; set; }
public string formattedAddress { get; set; }
public string locality { get; set; }
public string postalCode { get; set; }
}
public class GeocodePoint
{
public string type { get; set; }
public List<double> coordinates { get; set; }
public string calculationMethod { get; set; }
public List<string> usageTypes { get; set; }
}
public class Resource
{
public string __type { get; set; }
public List<double> bbox { get; set; }
public string name { get; set; }
public Point point { get; set; }
public Address address { get; set; }
public string confidence { get; set; }
public string entityType { get; set; }
public List<GeocodePoint> geocodePoints { get; set; }
public List<string> matchCodes { get; set; }
}
public class ResourceSet
{
public int estimatedTotal { get; set; }
public List<Resource> resources { get; set; }
}
public class RootObject
{
public string authenticationResultCode { get; set; }
public string brandLogoUri { get; set; }
public string copyright { get; set; }
public List<ResourceSet> resourceSets { get; set; }
public int statusCode { get; set; }
public string statusDescription { get; set; }
public string traceId { get; set; }
}
Since you already appear to be using DataContractJsonSerializer, let's stick with that. The best way to deserialize json is to first define a model which will capture the relevant data e.g.
public class JsonModel
{
public int StatusCode { get; set; }
public string StatusDescription { get; set; }
public string TraceId { get; set; }
...
}
Next, decorate the model so it's fit for deserialization
[DataContract]
public class JsonModel
{
[DataMember(Name = "statusCode")]
public int StatusCode { get; set; }
[DataMember(Name = "statusDescription")]
public string StatusDescription { get; set; }
[DataMember(Name = "traceId")]
public string TraceId { get; set; }
...
}
Then finally, perform the deserialization
using (var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonData)))
{
var serializer = new DataContractJsonSerializer(typeof(JsonModel));
var model = (JsonModel) serializer.ReadObject(memoryStream);
Console.WriteLine(model.StatusCode);
}
So how can access these element by name?
The other option for deserialization which would give you the ability to reference the properties by name would be to use a dynamic object e.g.
var model = new JavaScriptSerializer().Deserialize<dynamic>(jsonData);
Console.WriteLine(model["statusCode"]);
Add the classes for all Bing Maps REST Services from the URL below to your project:
JSON Data Contracts
Then, make sure that you add the using directive:
using BingMapsRESTService.Common.JSON;
and read the string as follows (where stream is a stream for your json):
var d = new DataContractJsonSerializer(typeof(Response));
var o = d.ReadObject(stream);