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
Related
I'm new to C#, I can't figure out how to parse JSON with an array of images. Everywhere basic examples with one picture.
For example, if JSON is simple:
{
"Rem": 1,
"name": "bandana for girls",
"articul": "18033325",
"Price": "1 332",
"Pict":"https://public/shop/products/28/00/120028/images/174872/174872.932x1242.jpg"
}
Then I create a class:
public class PriceList
{
public string Name { get; set; }
public string Rem { get; set; }
public string Price { get; set; }
public string articul { get; set; }
public string Pict { get; set; }
}
And then I pass it to XAML:
this.BindingContext = JsonConvert.DeserializeObject<IEnumerable<PriceList>>(json);
But how to process if there is an array of pictures in JSON?:
{
"Rem": 1,
"name": "bandana for girls",
"articul": "1805033325",
"Price": "1 332 ",
"Pict": [
"https://wa-data/public/shop/products/28/00/120028/images/174872/174872.932x1242.jpg",
"https://wa-data/public/shop/products/84/08/120884/images/183097/183097.932x1242.jpg"
]
}
I can not find such an example anywhere, tell me kind people how to solve this problem?
you can deserialize both your jsons using
PriceList priceList=JsonConvert.DeserializeObject<PriceList>(json);
the only difference is that for the second json
public string Pict { get; set; }
should be replaced by
public List<string> Pict { get; set; }
if you don't know what json you will get, this class will be working for both
public class PriceList
{
public string Name { get; set; }
public string Rem { get; set; }
public string Price { get; set; }
public string articul { get; set; }
public List<string> Pict { get; set; }
[Newtonsoft.Json.JsonConstructor]
public PriceList(JToken pict)
{
if (pict.Type.ToString() == "Array")
Pict = pict.ToObject<List<string>>();
else
{
Pict = new List<string>();
Pict.Add(pict.ToString());
}
}
public PriceList() {}
}
hello i've got some problems in c#(xamarin)
i followed XXX tutorials about pharsing..
I only need the Value.
Can someone tell me how i solve that problem?
my Json:
{
"Header":{
"Version":5,
"Device":"80",
"Timestamp":1610066048
},
"Data":{
"Inputs":[
{
"Number":2,
"AD":"A",
"Value":{
"Value":62.0,
"Unit":"1"
}
}
]
},
"Status":"OK",
"Status code":0
}
C#
var client = new WebClient();
string json = client.DownloadString("https://XXXXXXX.com/heizung.php");
Value1 news = JsonConvert.DeserializeObject<Value1>(json);
Ausgabe.Text = news.Value;
My Class
public class Header
{
public int Version { get; set; }
public string Device { get; set; }
public int Timestamp { get; set; }
}
public class Value1
{
public string Value { get; set; }
public string Unit { get; set; }
}
public class Input
{
public int Number { get; set; }
public string AD { get; set; }
public Value1 Value { get; set; }
}
public class Data
{
public List<Input> Inputs { get; set; }
}
public class Root
{
public Header Header { get; set; }
public Data Data { get; set; }
public string Status { get; set; }
public int Statuscode { get; set; }
}
Thanks, i hope y'all have a nice day.
Deserialize Root object and track value down:
Root news = JsonConvert.DeserializeObject<Root>(json);
Ausgabe.Text = news.Data.Inputs[0].Value.Value;
You should deserialize your json as a Root class:
var root = JsonConvert.DeserializeObject<Root>(json);
After the root object is deserialized you can select whatever value you need. E.g.:
var values = root.Data.Inputs.Select(i => i.Value.Value); // string sequence
I am new to C#
Following is the JSON string I am getting from the web API.
I am trying to store the JSON string into a class and then store the JSON string into an SQL table.
But the C# code is failing to deserialize JSON into class. And the message box returns the null exception error.
JSON
{
"Count":3,
"data":[
{
"Cost1":{
"amount":111,
"currencyCode":"ABC"
},
"Cost2":{
"amount":22.2,
"currencyCode":"XYZ"
},
"Id":"007"
},
{
"Cost1":{
"amount":555,
"currencyCode":"ABC"
},
"Cost2":{
"amount":444,
"currencyCode":"XYZ"
},
"Id":"008"
},
{
"Cost1":{
"amount":666,
"currencyCode":"ABC"
},
"Cost2":{
"amount":8882,
"currencyCode":"XYZ"
},
"Id":"009"
}
],
"pending":[
],
"#up":"Test Data"
}
C# Code
public class ParceJSN {
public int Count {
get;
set;
}
public string data {
get;
set;
}
public string pending {
get;
set;
}
public string up {
get;
set;
}
}
public void Main() {
Task < string > task = MakeRequest(db_token); //Returns the JSON string
var fr = task.Result;
ParceJSN rst = JsonConvert.DeserializeObject < ParceJSN > (fr.ToString());
MessageBox.Show(rst.TotalCount.ToString());
Dts.TaskResult = (int) ScriptResults.Success;
}
Your C# model is incorrect. Here's a really handy tool that I use when I need to generate C# classes based on some JSON - json2csharp.com
The correct class is:
public class Cost1 {
public int amount { get; set; }
public string currencyCode { get; set; }
}
public class Cost2 {
public double amount { get; set; }
public string currencyCode { get; set; }
}
public class Datum {
public Cost1 Cost1 { get; set; }
public Cost2 Cost2 { get; set; }
public string Id { get; set; }
}
public class Root {
public int Count { get; set; }
public List<Datum> data { get; set; }
public List<object> pending { get; set; }
[JsonProperty("#up")]
public string Up { get; set; }
}
Now that you have the correct model, you can now do the following to deserialize your JSON string into a Root object which is defined above:
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(YOUR_JSON_STRING);
I can't seem to be bale to convert Json to my desired List class.
I got the Json file and passed it to Json to C#
and it generated the class:
public class Customers
{
[JsonProperty("Customers")]
public string Oid { get; set; }
[JsonProperty("Customers")]
public string Name { get; set; }
[JsonProperty("Customers")]
public string Title { get; set; }
[JsonProperty("Customers")]
public string Kwdikos { get; set; }
[JsonProperty("Customers")]
public string AFM { get; set; }
[JsonProperty("Customers")]
public string Email { get; set; }
[JsonProperty("Customers")]
public string DOY { get; set; }
[JsonProperty("Customers")]
public string Occupation { get; set; }
[JsonProperty("Customers")]
public int FPA { get; set; }
}
public class CustomersList
{
[JsonProperty("Customers")]
public List<Customers> _customersList { get; set; }
}
and I am using the code to get the Json to my List Class like this:
var content = await response.Content.ReadAsStringAsync();
var customers = JsonConvert.DeserializeObject<List<CustomersList>>(content, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
But I get an error saying:
Newtonsoft.Json.JsonSerliazitaionException : 'Error converting value
"(My Json file)" to type
'System.Collections.Generic.List`1[DemoProject6.CustomersList]'. Path
'', line 1, position 37574.'
Any Idea on how to solve this? Thank you for your time !!!
JsonPropertyAttribute specified for the property, the name in JSON texte. But in your example, all properties have [JsonProperty("Customers")]. The JSON generated by your model will be :
{
"Customer": [{
"Customers": "Oid value",
"Customers": "Name value",
"Customers": "Title value",
...
}]
}
In JSON, you can't have by level some property with the same name.
By default, the json property's name is class property's name.
Solution :
public class Customers
{
public string Oid { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Kwdikos { get; set; }
public string AFM { get; set; }
public string Email { get; set; }
public string DOY { get; set; }
public string Occupation { get; set; }
public int FPA { get; set; }
}
Then
var content = await response.Content.ReadAsStringAsync();
var customers = JsonConvert.DeserializeObject<List<Customers>>(content);
edit:
I think the response's content isn't well formatted.
Maybe you can try :
var content = await response.Content.ReadAsStringAsync();
var customersJson = Regex.Unescape(content.Substring(1, content.Length - 2));
var customers = JsonConvert.DeserializeObject<List<Customers>>(customersJson);
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);