How to set up class for json? - c#

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);

Related

How to generate a JSON class with dynamic name

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(),
});

How to fix Error while converting Json string to Object C#?

Im using C# to get a file from my local pc data folder.
This is the code to do that:
var _rootpath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + directory;
var ENC = new Encryption();
var s = File.ReadAllText(_rootpath + "json");
var x = ENC.RijndaelDecrypt(s, App.EncryptionPassword);
This works fine so far.
x got now this value (so this is the string I want to convert to an object) :
{
"items":[
{
"id":194,
"guid":"594394",
"name":"Test",
"connectorId":248,
"customerId":1,
"customerName":"company",
"connectorTypeId":10,
"connectorTypeIcon":null,
"connectorCategoryId":1,
"vendor":"FasterForward",
"isActive":true,
"shopId":null,
"sku":null,
"workerBearerToken":"",
"workerUri":"http://localhost:9000"
}
],
"responseStatus":null
}
After this I want to convert this to an object
var _response = JsonConvert.DeserializeObject<CrmJobListResponse>(x);
This line gives an error:
{"Error converting value x to type 'ServiceModel.CrmJobListResponse'. Path '', line 1, position 991."}
ServiceModel.CrmJobListResponse:
namespace ServiceModel
{
public class CrmJobListResponse : ResponseBase
{
public CrmJobListResponse();
public List<CrmJob> Items { get; set; }
}
}
CrmJob class:
namespace ServiceModel.DTO
{
public class CrmJob : IHasId<int>
{
public CrmJob();
[Ignore]
public string WorkerBearerToken { get; set; }
[PropertyValue("sku")]
public string SKU { get; set; }
[PropertyValue("shop_id")]
public string ShopId { get; set; }
public bool IsActive { get; set; }
public string Vendor { get; set; }
public int ConnectorCategoryId { get; set; }
[Ignore]
public string WorkerRefreshToken { get; set; }
public string ConnectorTypeIcon { get; set; }
public string CustomerName { get; set; }
public int CustomerId { get; set; }
public int ConnectorId { get; set; }
[PropertyValue("jobname")]
public string Name { get; set; }
public string Guid { get; set; }
public int Id { get; set; }
public int ConnectorTypeId { get; set; }
[Ignore]
public string WorkerUri { get; set; }
}
}
Does anyone know why it can't convert my Json string to an object?
I didn't made the code myself, but I don't see why It should go wrong...
If you have a hard time creating DTOs you have some tools that may assist you https://app.quicktype.io/
You can also use paste special in VS to paste a Json directy to a C# class.
This also shows you if you malformed a Json.

Json.Net deserialize JSON objects

I've popped consuming a WebServer returning the Json bellow, and I'm not able to convert it to an object.
Json
{
"success":true,
"data":{
"24486146360":{
"rfid":"123465789456",
"products":[
{
"sale_id":35,
"quantity":2,
"price":"1",
"total":"2",
"unit":"uni",
"sku":14
},
{
"sale_id":36,
"quantity":2,
"price":"2.5",
"total":"5",
"unit":"uni",
"sku":17
}
]
},
"24758345953":{
"rfid":"2129",
"products":[
{
"sale_id":39,
"quantity":1,
"price":"10",
"total":"10",
"unit":"ml",
"sku":19998
}
]
},
"64577015900":{
"rfid":"1934",
"products":[
{
"sale_id":40,
"quantity":1,
"price":"10",
"total":"10",
"unit":"ml",
"sku":19998
}
]
},
"56768990934":{
"rfid":"1746",
"products":[
{
"sale_id":46,
"quantity":1,
"price":"8.00",
"total":"8",
"unit":"UN",
"sku":20
}
]
}
}
}
I used json2sharp to generate a class from the JSON, I then cleaned up the class and was left with the following:
My Class create help for json2sharp
public class Consumo
{
public string rfid { get; set; }
public List<ConsumoProduto> products { get; set; }
}
public class ConsumoProduto
{
public int sale_id { get; set; }
public double quantity { get; set; }
public string price { get; set; }
public string total { get; set; }
public string unit { get; set; }
public int sku { get; set; }
}
public class RetornoConsumo
{
[JsonProperty("success")]
public bool Processado { get; set; }
[JsonProperty("data")]
public List<Consumo> Registro { get; set; }
}
My Problem
how do I convert Json to a valid object using Json.Net?
Test
I tried to do this and I could not
Dictionary<string, RetornoConsumo> _featuredArticles = JsonConvert.DeserializeObject<Dictionary<string, RetornoConsumo>>(json);
In your RetornoConsumo class, the Registro property needs to be a Dictionary<string, Consumo> not a List<Consumo>.
public class RetornoConsumo
{
[JsonProperty("success")]
public bool Processado { get; set; }
[JsonProperty("data")]
public Dictionary<string, Consumo> Registro { get; set; }
}
Then, you need to deserialize the JSON into the RetornoConsumo class:
var data = JsonConvert.DeserializeObject<RetornoConsumo>(json);
Fiddle: https://dotnetfiddle.net/vfhdXp

JSON C# DeserializeObject Error with Newtonsoft.Json

I have a JSON string that I am getting from the BaseCamp API. I know for a fact that the JSON is valid, however, I am not able to DeserializeObject using Newtonsoft.Json.
I get an error saying:
Cannot deserialize the current JSON array (e.g.[1,2,3]) into type BaseCamp.Code.Projects+RootObject because the type requires a JSON objet (e.g. {"name":"value"}) to deserialize correctly.
The JSON (Unformated What is returned from the API Minus the URL's Values)
[
{
"id":6656986,
"name":"Physics Revamp",
"description":"ISU department of physics website redesign",
"archived":false,
"is_client_project":true,
"created_at":"2014-08-07T10:59:29.000-05:00",
"updated_at":"2014-10-30T09:18:01.000-05:00",
"trashed":false,
"color":"2c5322",
"draft":false,
"template":false,
"last_event_at":"2014-10-30T09:18:01.000-05:00",
"starred":false,
"url":"xxxxxxxxxxxxxxxxxxxxxxx",
"app_url":"xxxxxxxxxxxxxxx"
},
{
"id":7178664,
"name":"Physics Videos",
"description":"",
"archived":false,
"is_client_project":false,
"created_at":"2014-10-02T08:34:46.000-05:00",
"updated_at":"2014-10-23T08:40:17.000-05:00",
"trashed":false,
"color":"660099",
"draft":false,
"template":false,
"last_event_at":"2014-10-23T08:40:17.000-05:00",
"starred":false,
"url":"xxxxxxxxxxxxxxxxxxxxxxx",
"app_url":"xxxxxxxxxxxxxxxxxxx"
},
{
"id":6685451,
"name":"WZND Website 2014",
"description":"",
"archived":false,
"is_client_project":true,
"created_at":"2014-08-11T13:25:51.000-05:00",
"updated_at":"2014-10-30T11:26:39.000-05:00",
"trashed":false,
"color":"3185c5",
"draft":false,
"template":false,
"last_event_at":"2014-10-30T11:26:39.000-05:00",
"starred":false,
"url":"xxxxxxxxxxxxxxxxxx",
"app_url":"xxxxxxxxxxxxxxxxx"
}
]
My C# class:
public class Projects
{
public class RootObject
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public bool archived { get; set; }
public bool is_client_project { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public bool trashed { get; set; }
public string color { get; set; }
public bool draft { get; set; }
public bool template { get; set; }
public string last_event_at { get; set; }
public bool starred { get; set; }
public string url { get; set; }
public string app_url { get; set; }
}
}
I am assuming something is wrong with the way my class is set up, but I can't see it.
You need to convert to an array of RootObject:
var json = JsonConvert.DeserializeObject<Projects.RootObject[]>(response);
or list (or any other collection you want for that matter)...
var json = JsonConvert.DeserializeObject<List<Projects.RootObject>>(response);

Parse JSON object in C#

I use JSON.NET and I would like to parse the following object which I get from a WebService. Can someone post an example on how to do that?
#"{""MessageType"":0,
""Message"":""Success"",
""Value"":[
{""listId"":1,
""listName"":""DemoList"",
""itemInList"":[
{
""fromDate"":""\/Date(1228946400000)\/"",
""fromLocation"":null,
""toLocation"":null,
""originalRequest"":""water"",
""creationDate"":""\/Date(1339448400000)\/"",
""typeId"":1
},
{
""fromDate"":null,
""fromLocation"":null,
""toLocation"":null,
""originalRequest"":""gala"",
""creationDate"":""\/Date(1304370000000)\/"",
""typeId"":1
}
]}
]}"
JSON Object
{
"MessageType":0,
"Message":"UserLists",
"Value":
[
{
"listId":1,
"listName":"DemoList",
"itemInList"
[
{
"fromDate":"\/Date(1228946400000)\/",
"fromLocation":null,
"toLocation":null,
"originalRequest":"water",
"creationDate":"\/Date(1339448400000)\/",
"typeId":1
},
{
"fromDate":null,
"fromLocation":null,
"toLocation":null,
"originalRequest":"gala",
"creationDate":"\/Date(1304370000000)\/",
"typeId":1
}
],
"numberOfItems":2
}
]
}
Thanks.
You need to create some entity like this:
public class Entity
{
public int MessageType { get; set; }
public string Message { get; set; }
public List<EntityValue> Value { get; set; }
}
public class EntityValue
{
public int listId { get; set; }
public string listName { get; set; }
public List<ItemInList> itemInList { get; set; }
}
public class ItemInList
{
public DateTime? fromDate { get; set; }
public string fromLocation { get; set; }
public string toLocation { get; set; }
public string originalRequest { get; set; }
public DateTime creationDate { get; set; }
public int typeId { get; set; }
}
The entity must has the same structure like the json data.
And you can call the Method:
JsonConvert.DeserializeObject<Entity>(json);
If it has any exception,you need to adjust the entities until it works.
Please read the below link for parsi in metro style application.
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh770287.aspx

Categories

Resources