This question already has an answer here:
Deserializing JSON into an object
(1 answer)
Closed 6 years ago.
This is my json file
{
"UseCase1": {
"UseCaseId": "Usecase1",
"UseCaseDescription": "description1"
},
"UseCase2": {
"UseCaseId": "Usecase2",
"UseCaseDescription": "description2"
}
}
This is my class
public class UseCase
{
public string UseCaseId { get; set;}
public string UseCaseDescription { get; set;}
}
How to assign the json elements to a list of this class(UseCase)
I tried the below code, but it is not working
string Json = System.IO.File.ReadAllText(#"D:\ENERGY METER\ENERGY METER –IRP\SourceCode\EDMI.EnergyMeterPOC\EDMI.EnergyMeterPOC.Repository\DataSource\UseCaseData.json");
JavaScriptSerializer ser = new JavaScriptSerializer();
var personlist = ser.Deserialize<List<UseCase>>(Json);
return personlist;
You need to look at your Json again.
When placed into a tool like JSON Utils, you end up with the following.
public class UseCase1
{
public string UseCaseId { get; set; }
public string UseCaseDescription { get; set; }
}
public class UseCase2
{
public string UseCaseId { get; set; }
public string UseCaseDescription { get; set; }
}
public class RootObject
{
public UseCase1 UseCase1 { get; set; }
public UseCase2 UseCase2 { get; set; }
}
In order for your object to be in a list it woudl first have to be an array which your file is not.
You Json file would have to be looking like this to satisfy your UseCase collection requirement
{
"UseCases": [
{
"UseCaseId": "Usecase1",
"UseCaseDescription": "description1"
},
{
"UseCaseId": "Usecase2",
"UseCaseDescription": "description2"
}]
}
which would have the following classes when deserialized...
public class UseCase
{
public string UseCaseId { get; set; }
public string UseCaseDescription { get; set; }
}
public class RootObject
{
public List<UseCase> UseCases { get; set; }
}
Related
I don't know if there is an existing name for that case, but I'm trying to retrieve data from NASA API (https://api.nasa.gov/) and I have a simple challenge to catch a list of objects near earth. Here is the JSON response I have from the GET request I do to "https://api.nasa.gov/neo/rest/v1/feed?...."
{
"links": {
"next": "http://www.neowsapp.com/rest/v1/feed?start_date=2021-07-04&end_date=2021-07-04&detailed=false&api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym",
"prev": "http://www.neowsapp.com/rest/v1/feed?start_date=2021-07-02&end_date=2021-07-02&detailed=false&api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym",
"self": "http://www.neowsapp.com/rest/v1/feed?start_date=2021-07-03&end_date=2021-07-03&detailed=false&api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym"
},
"element_count": 6,
"near_earth_objects": {
"2021-07-03": [
{
"links": {
"self": "http://www.neowsapp.com/rest/v1/neo/3701710?api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym"
},
"id": "3701710",
"neo_reference_id": "3701710",
"name": "(2014 WF497)",
"nasa_jpl_url": "http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=3701710",
"absolute_magnitude_h": 20.23,
"estimated_diameter": {
"kilometers": {
}
And that's the way it is built in Visual Studio (using the Special Paste option for JSON)
public class NearEarthObject
{
public Links links { get; set; }
public int element_count { get; set; }
public Near_Earth_Objects near_earth_objects { get; set; }
}
public class Links
{
public string next { get; set; }
public string prev { get; set; }
public string self { get; set; }
}
public class Near_Earth_Objects
{
public _20210703[] _20210703 { get; set; }
}
public class _20210703
{
public Links1 links { get; set; }
public string id { get; set; }
public string neo_reference_id { get; set; }
public string name { get; set; }
public string nasa_jpl_url { get; set; }
public float absolute_magnitude_h { get; set; }
public Estimated_Diameter estimated_diameter { get; set; }
public bool is_potentially_hazardous_asteroid { get; set; }
public Close_Approach_Data[] close_approach_data { get; set; }
public bool is_sentry_object { get; set; }
}
The question is, inside of the element "near_earth_objects", there is an element called "2021-07-03" (the date of the data I requested), the problem is that I am trying to include it into a DataGridView made in .NET C# (Windows Forms, but that doesn't matters here, I think) and the user wants to get the information by date. So, "2021-07-03" is a valid member just for one day, and the user should be able to get data from multiple days.
So, is there a way in C# to get all child objects inside of near_earth_objects without knowing their names since there will be the option to search for asteroids from date X to Y in my application?
Using System.Text.Json
The API response will map to the following classes
public class Neo
{
public Links Links { get; set; }
public int ElementCount { get; set; }
public Dictionary<string, List<NearEarthObject>> NearEarthObjects { get; set; }
}
public class Links
{
public string Next { get; set; }
public string Prev { get; set; }
public string Self { get; set; }
}
public class NearEarthObject
{
public Links Links { get; set; }
public string Id { get; set; }
public string Name { get; set; }
// Other properties
}
The NearEarthObjects is simply a Dictionary, where the key is the formatted date and value is a List containing NearEarthObject
The PropertyNamingPolicy will allow us to support the API's underscore property naming convention.
public class UnderscoreNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
return name.Underscore();
}
}
Example usage
// using using System.Text.Json;
var response = await new HttpClient().GetStringAsync(url);
var neo = JsonSerializer.Deserialize<Neo>(response, new JsonSerializerOptions
{
PropertyNamingPolicy = new UnderscoreNamingPolicy()
});
foreach(var neos in neo.NearEarthObjects)
{
Console.WriteLine(neos.Key);
}
use System.Text.Json, JsonNamingPolicy
demo code
public class DynamicNamePolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
var today = DateTime.Today.ToString("yyyy-MM-dd");
if (name.Equals("DateData")) //model property name
return today; //convert to json string property name
return name;
}
}
//data deserialize
string data = ""; //json string
var obj = JsonSerializer.Deserialize<NearEarthObject>(data, new JsonSerializerOptions
{
PropertyNamingPolicy = new DynamicNamePolicy(),
});
This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
How to auto-generate a C# class file from a JSON string [closed]
(3 answers)
Closed 2 years ago.
I just wanna ask if how to implement in c# a json data with array structure. This is the sample data below:
{
"contact":
{
"contact_type_ids": ["CUSTOMER"],
"name":"JSON Sample ResellerAVP",
"main_address":
{
"address_type_id":"ACCOUNTS",
"address_line_1":"Ayala Hills",
"city":"Muntinlupa",
"region":"NCR",
"postal_code":"1770",
"country_group_id":"ALL"
}
}
}
JSON overview:
{ } - Object
[ ] - Array
"a": something - Property
A property can have an object, array, or value type as its value. For example:
{
"a": true,
"b": "hello",
"c": 5.2,
"d": 1,
"e": { "eChildProperty": "test" },
"f": [ "a", "b", "c" ]
}
Let's start transcribing this JSON into classes!
{
"contact":
{
"contact_type_ids": ["CUSTOMER"],
"name":"JSON Sample ResellerAVP",
"main_address":
{
"address_type_id":"ACCOUNTS",
"address_line_1":"Ayala Hills",
"city":"Muntinlupa",
"region":"NCR",
"postal_code":"1770",
"country_group_id":"ALL"
}
}
}
OK, so we have a root object with a property "contact", which is also an object. Let's represent both of those:
public class RootObject
{
public Contact Contact { get; set; }
}
public class Contact
{
}
Now we need to add Contact's properties. It has 3: contact_type_ids is an array of strings, name is a string, and main address is a complex object. Let's represent those:
public class Contact
{
[JsonProperty("contact_type_ids")]
public IList<string> ContactTypeIds { get; set; } // I'm using an IList, but any collection type or interface should work
public string Name { get; set; }
[JsonProperty("main_address")]
public Address MainAddress { get; set; }
}
public class Address
{
}
Finally we need to work on the Address object:
public class Address
{
[JsonProperty("address_type_id")]
public string AddressTypeId { get; set; }
[JsonProperty("address_line_1")]
public string AddressLine1 { get; set; }
public string City { get; set; }
public string Region { get; set; }
[JsonProperty("postal_code")]
public string PostalCode { get; set; }
[JsonProperty("country_group_id")]
public string CountryGroupId { get; set; }
}
Putting this all together we get:
public class RootObject
{
public Contact Contact { get; set; }
}
public class Contact
{
[JsonProperty("contact_type_ids")]
public IList<string> ContactTypeIds { get; set; } // I'm using an IList, but any collection type or interface should work
public string Name { get; set; }
[JsonProperty("main_address")]
public Address MainAddress { get; set; }
}
public class Address
{
[JsonProperty("address_type_id")]
public string AddressTypeId { get; set; }
[JsonProperty("address_line_1")]
public string AddressLine1 { get; set; }
public string City { get; set; }
public string Region { get; set; }
[JsonProperty("postal_code")]
public string PostalCode { get; set; }
[JsonProperty("country_group_id")]
public string CountryGroupId { get; set; }
}
And we can use it like so:
RootObject deserialized = JsonConvert.DeserializeObject<RootObject>(jsonString);
Try it online
JSON isn't complicated by any stretch of the imagination. It's really simple to understand and manually convert into classes just by looking at the data you have.
I am working with opentdb.com api and have no idea how to access data in this json:
{
"response_code":0,
"results": [
{
"category":"Animals",
"type":"multiple",
"difficulty":"easy",
"question":"What is the scientific name for modern day humans?",
"correct_answer":"Homo Sapiens",
"incorrect_answers":[
"Homo Ergaster",
"Homo Erectus",
"Homo Neanderthalensis"
]
},
{
"category":"Entertainment: Cartoon & Animations",
"type":"multiple",
"difficulty":"easy",
"question":"Who voices for Ruby in the animated series RWBY?",
"correct_answer":"Lindsay Jones",
"incorrect_answers":[
"Tara Strong",
"Jessica Nigri",
"Hayden Panettiere"
]
}
]
}
I am using Newtonsoft.Json and i tried this with only 1 Question but im geting an error that says that key value is wrong..
class Trivia
{
public Trivia(string json)
{
JObject jObject = JObject.Parse(json);
JToken jresults = jObject["results"];
category = (string)jresults["category"];
type = (string)jresults["type"];
difficulty = (string)jresults["difficulty"];
question = (string)jresults["question"];
correct_answer = (string)jresults["correct_answer"];
incorrect_answers = jresults["incorrect_answers"].ToArray();
}
public string category { get; set; }
public string type { get; set; }
public string difficulty { get; set; }
public string question { get; set; }
public string correct_answer { get; set; }
public Array incorrect_answers { get; set; }
}
Copy from json text and in new class in visual studio Edit-->Paste Special-->Paste JSON As Classes
public class Rootobject
{
public int response_code { get; set; }
public Result[] results { get; set; }
}
public class Result
{
public string category { get; set; }
public string type { get; set; }
public string difficulty { get; set; }
public string question { get; set; }
public string correct_answer { get; set; }
public string[] incorrect_answers { get; set; }
}
using namespace
using Newtonsoft.Json;
response is value get from your service
var outdeserialized = JsonConvert.DeserializeObject<Rootobject>(response);
For deserialisation I usually use an object with the same property names as found in the JSon and JsonConvert.DeserializeObject<Des>(jsonstring).
But now I came across this:
{
"id": 0815,
"name": "whatever"
"addedInfo": {
"thisisinteresting": 4711,
"id_str": "2336"
}
}
How can I tell JSon.Net to pull the 'thisisinteresting' part of the sub category into a class like:
class Des
{
int id;
string name;
int thisisinteresting;
}
The trivial way would be to actually model your class to the JSON structure:
public class AddedInfo
{
public int thisisinteresting { get; set; }
public string id_str { get; set; }
}
public class RootObject
{
public int id { get; set; }
public string name { get; set; }
public AddedInfo addedInfo { get; set; }
}
Then add a property to the RootObject to emit the property:
public class RootObject
{
public int id { get; set; }
public string name { get; set; }
public AddedInfo addedInfo { get; set; }
[JsonIgnore]
public int thisisinteresting { get { return addedInfo.thisisinteresting; } }
}
There are alternatives like creating a custom serializer or using JObject and deserialize the structure yourself, but I won't go into that. If you need to parse the JSON anyway, the price to deserialize it entirely is small.
I have to write a WCF webservice in dot net in nested Json structured below. I know how to write simple json but not sure to make it nested for `results
{
"version": 2,
"results": [{
"company": "ABC Company Inc.",
"city": "Sacramento",
"state": "CA"
}
]
}
What I am doing is :
file1.cs
namespace Test
{
public class file1
{
public class child
{
[DataMember]
public string version { get; set; }
}
public class parent
{
[DataMember]
public string company { get; set; }
[DataMember]
public string city { get; set; }
}
}
}
In file2.svc.cs
public List<file1> method()
{
List<file1.child> result = new List<file1.child>();
List<file1.parent> result1 = new List<file1.parent>();
List<file1> final = new List<file1>();
foreach (DataRow catt1 in dtcategory.Rows)
{
result.Add(new file1.child()
{
version= catt1["version"].ToString(),
});
result1.Add(new file1.parent() {
company= catt1["company"].ToString(),
city= catt1["city"].ToString(),
});
final.Add(new file1()
{
});
}
return Add;
}
Please let me where I am going wrong
Class Structure:
public class class1
{
[DataMember]
public string version {get;set;}
[DataMember]
public List<class2> results {get;set;}
}
public class class2
{
[DataMember]
public string company {get;set;}
[DataMember]
public string city{get;set;}
[DataMember]
public string state {get;set;}
}
Your question is sort of unclear. However, if you are asking "how can I design my classes file1.child and file1.parent so that, when serialized by DataContractJsonSerializer or Json.NET, they produce the JSON shown", then you can do:
public class file1
{
[DataContract]
public class child
{
[DataMember(Name="version")]
public string Version { get; set; }
[DataMember(Name="results")]
public List<parent> Results { get; set; }
}
[DataContract]
public class parent
{
[DataMember(Name="company")]
public string Company { get; set; }
[DataMember(Name="city")]
public string City { get; set; }
[DataMember(Name="state")]
public string State { get; set; }
}
}
Note that, given your class names, parent is contained inside child, which is counterintuitive. You might want to change those names.