I'm in trouble with this json:
{
"tester": [
{
"type": {
"ID": "R89d",
"Description": "Test",
"lastUpdated": "2016-03-20 20:45:09",
},
"specification": {}
},
{
"type": {
"ID": "RB01",
"Description": "Another test",
"lastUpdated": null
},
"specification": {
"0": {
"ID": "RB01",
"number": 1,
"Type": "RB"
},
"1": {
"ID": "RB01",
"number": 3,
"Type": "RB"
}
}
},
{
"type": {
"ID": "RT40",
"Description": "Test 2",
"lastUpdated": null,
},
"specification": {}
}
]
}
in particular when I put it into json2c# site I got this class:
public class Type
{
public string ID { get; set; }
public string Description { get; set; }
public string lastUpdated { get; set; }
}
public class __invalid_type__0
{
public string ID { get; set; }
public int number { get; set; }
public string Type { get; set; }
}
public class __invalid_type__1
{
public string ID { get; set; }
public int number { get; set; }
public string Type { get; set; }
}
public class Specification
{
public __invalid_type__0 __invalid_name__0 { get; set; }
public __invalid_type__1 __invalid_name__1 { get; set; }
}
public class Tester
{
public Type type { get; set; }
public Specification specification { get; set; }
}
public class RootObject
{
public List<Tester> tester { get; set; }
}
I don't know why the site return me invalid type 'cause the json syntax is correct. My goal is create a class that allow me to read all properties of specification, how you can see in the json there is an array of object. What I need to do is create something that allow me to access to all specification object value as ID - Number - Type. Actually I managed it only with Type with something like this:
string responseText = "json above";
var obj = JsonConvert.DeserializeObject<RootObject>(responseText);
foreach(var item in obj.Tester){ //loop through Tester item
//what I need:
foreach(var spec in item.specification){ //not possible
spec.Description; ...
}
}
Problem is here:
"specification": {
"0": {
"ID": "RB01",
"number": 1,
"Type": "RB"
},
"1": {
"ID": "RB01",
"number": 3,
"Type": "RB"
}
In c# names cannot start with digit. Generator cannot name type "0" and "1"
EDIT
If you can change json then modify it in this way:
"specification": [
{
"ID": "RB01",
"number": 1,
"Type": "RB"
},
{
"ID": "RB01",
"number": 3,
"Type": "RB"
}
]
So change to array give this structure:
public class Type
{
public string ID { get; set; }
public string Description { get; set; }
public string lastUpdated { get; set; }
}
public class Specification
{
public string ID { get; set; }
public int number { get; set; }
public string Type { get; set; }
}
public class Tester
{
public Type type { get; set; }
public List<Specification> specification { get; set; }
}
public class RootObject
{
public List<Tester> tester { get; set; }
}
public class Type
{
public string ID { get; set; }
public string Description { get; set; }
public string lastUpdated { get; set; }
}
public class Specification
{
public string ID { get; set; }
public int number { get; set; }
public string Type { get; set; }
}
public class Tester
{
public Type[] types { get; set; }
public Specification[] specifications { get; set; }
}
public class RootObject
{
public List<Tester> tester { get; set; }
}
specification should be an array:
"specification": [
{
"ID": "RB01",
"number": 1,
"Type": "RB"
},
....
]
and c# implementation too:
public class Tester
{
public Type type { get; set; }
public Specification[] specification { get; set; }
}
or List<Specification>:
public class Tester
{
public Type type { get; set; }
public List<Specification> specification { get; set; }
}
and Specification itself:
public class Specification
{
public string ID { get; set; }
public int number { get; set; }
public string Type { get; set; }
}
Related
Working on pulling work items from Azure Devops:
According to this article, the response looks like so: https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/list?view=azure-devops-rest-6.0
{
"count": 2,
"value": [
{
"id": 297,
"rev": 1,
"fields": {
"System.AreaPath": "Fabrikam-Fiber-Git",
"System.Title": "Customer can sign in using their Microsoft Account",
...
}
},
{
"id": 298,
"rev": 1,
"fields": {
"System.AreaPath": "Fabrikam-Fiber-Git",
"System.Title": "Customer can log out",
...
}
}
]
}
I am assuming that an object for it would look something like this:
public class WorkItemModel
{
public int id { get; set; }
public int rev { get; set; }
public FieldsModel fields { get; set; }
}
public class FieldsModel
{
public string AreaPath { get; set; }
public string Title { get; set; }
}
But how do I deserialize this into the proper objects? And how does the "System.AreaPath" and "System.Title" get handled?
You can create Models as below:
public class FieldsModel
{
[JsonProperty("System.AreaPath")]
public string SystemAreaPath { get; set; }
[JsonProperty("System.Title")]
public string SystemTitle { get; set; }
}
public class WorkItemModel
{
public int id { get; set; }
public int rev { get; set; }
public FieldsModel fields { get; set; }
}
public class Root
{
public int count { get; set; }
public List<WorkItemModel> value { get; set; }
}
//using as below
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
Community,
I want to read all the values from this json. I am using C#. How do I manage do that? I am trying to use the openroute service distance matrix.
My Idea:
string responseData = await response.Content.ReadAsStringAsync();
var jobject = JObject.Parse(responseData);
var onlydistance = jobject.SelectTokens("$.distances[*]")
.Values<double>()
.ToArray();
My JSON:
{
"distances": [[0, 108628.26, 2669713, 11595025], [108952.97, 0, 2674477.75, 11609762], [2688555, 2681139.5, 0, 8405009], [11596626, 11611808, 8734262, 0]],
"destinations": [
{
"location": [9.700817, 48.476406],
"snapped_distance": 118.92
},
{
"location": [9.207773, 49.153882],
"snapped_distance": 10.54
},
{
"location": [37.572963, 55.801279],
"snapped_distance": 17.45
},
{
"location": [115.665017, 38.100717],
"snapped_distance": 648.79
}
],
"sources": [
{
"location": [9.700817, 48.476406],
"snapped_distance": 118.92
},
{
"location": [9.207773, 49.153882],
"snapped_distance": 10.54
},
{
"location": [37.572963, 55.801279],
"snapped_distance": 17.45
},
{
"location": [115.665017, 38.100717],
"snapped_distance": 648.79
}
],
"metadata":
{
"attribution": "openrouteservice.org | OpenStreetMap contributors",
"service": "matrix",
"timestamp": 1603348601609,
"query":
{
"locations": [[9.70093, 48.477473], [9.207916, 49.153868], [37.573242, 55.801281], [115.663757, 38.106467]],
"profile": "cycling-road",
"responseType": "json",
"metricsStrings": ["DISTANCE"],
"metrics": ["distance"],
"units": "m"
},
"engine":
{
"version": "6.3.0",
"build_date": "2020-10-19T02:01:48Z",
"graph_date": "2020-10-12T06:58:07Z"
}
}
}
Use a generator/converter to generate Json Classes eg: https://json2csharp.com/
Sample code:
public Form1()
{
InitializeComponent();
string jsonData = File.ReadAllText(#"c:\root\t01.json");
Root root = JsonConvert.DeserializeObject<Root>(jsonData);
}
public class Root {
public List<List<double>> distances { get; set; }
public List<Destination> destinations { get; set; }
public List<Source> sources { get; set; }
public Metadata metadata { get; set; }
}
public class Destination {
public List<double> location { get; set; }
public double snapped_distance { get; set; }
}
public class Source {
public List<double> location { get; set; }
public double snapped_distance { get; set; }
}
public class Query {
public List<List<double>> locations { get; set; }
public string profile { get; set; }
public string responseType { get; set; }
public List<string> metricsStrings { get; set; }
public List<string> metrics { get; set; }
public string units { get; set; }
}
public class Engine {
public string version { get; set; }
public DateTime build_date { get; set; }
public DateTime graph_date { get; set; }
}
public class Metadata {
public string attribution { get; set; }
public string service { get; set; }
public long timestamp { get; set; }
public Query query { get; set; }
public Engine engine { get; set; }
}
I am trying to deserialize this JSON, but I keep getting errors. Can someone please help me? Where did I make a mistake?
JSON:
{
"totalItems": 63,
"items": [
{
"id": 100039812,
"group": {
"code": "DD",
"description": "Delivery Documents"
},
"type": {
"code": "READ",
"description": "Logs"
},
"reference": "ARLDR",
"date": "2015-03-24T00:00:00",
"description": "ALogs",
"notes": "",
"lastUpdateDate": "2015-03-24T14:06:42.063",
"location": "BOX A001",
"metadata": {}
},
{
"id": 100039813,
"group": {
"code": "DD",
"description": "Delivery Documents"
},
"type": {
"code": "BL",
"description": "Logbooks"
},
"reference": "BALB",
"date": "2015-03-24T00:00:00",
"description": "Logbooks",
"notes": "",
"lastUpdateDate": "2015-03-24T14:07:42.44",
"location": "BOX A001",
"metadata": {}
}
]
}
public class Documents
{
public int totalItems { get; set; }
public List<doc_items> items { get; set; }
}
public class doc_items
{
public int id { get; set; }
public List<group_items> group { get; set; }
public List<type_items> type { get; set; }
public string reference { get; set; }
public string date { get; set; }
public string description { get; set; }
public string notes { get; set; }
public string lastUpdateDate { get; set; }
public string location { get; set; }
public List<metadata_list> metadata { get; set; }
}
public class group_items
{
public string code { get; set; }
public string description { get; set; }
}
public class type_items
{
public string code { get; set; }
public string description { get; set; }
}
public class metadata_list
{
}
Then I call this:
Documents myDocuments = JsonConvert.DeserializeObject<Documents>(responsetext.ToString());
and receive the following error:
Error: Newtonsoft.Json.JsonSerializationException:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type System.Collections.Generic.List`1[AerData.Ranorex.Web.Records.API_Documents+Documents]' because the type requires a JSON array (e.g. [...
On the contrary 'group', 'type' and 'metadata' are not arrays so modify your class to:
public class doc_items
{
public int id { get; set; }
public group_items group { get; set; }
public type_items type { get; set; }
public string reference { get; set; }
public string date { get; set; }
public string description { get; set; }
public string notes { get; set; }
public string lastUpdateDate { get; set; }
public string location { get; set; }
public metadata_list metadata { get; set; }
}
Given from the definition of the Documents class, the group property of an doc_items has to be an array. In your given JSON it's an object. The same holds for the type property
I recommend using a converter like this: http://json2csharp.com/#
Try this:
class Program
{
static void Main(string[] args)
{
var sr = new StreamReader("json.json");
var jsonText = sr.ReadToEnd();
Documents myDocuments = JsonConvert.DeserializeObject<Documents>(jsonText);
}
}
public class group_items
{
public string code { get; set; }
public string description { get; set; }
}
public class type_items
{
public string code { get; set; }
public string description { get; set; }
}
public class metadata_list
{
}
public class doc_items
{
public int id { get; set; }
public group_items GroupItems { get; set; }
public type_items TypeItems { get; set; }
public string reference { get; set; }
public string date { get; set; }
public string description { get; set; }
public string notes { get; set; }
public string lastUpdateDate { get; set; }
public string location { get; set; }
public metadata_list MetadataList { get; set; }
}
public class Documents
{
public int totalItems { get; set; }
public List<doc_items> items { get; set; }
}
Your data file json.json
{
"totalItems": 63,
"items": [
{
"id": 100039812,
"group": {
"code": "DD",
"description": "Delivery Documents"
},
"type": {
"code": "READ",
"description": "Logs"
},
"reference": "ARLDR",
"date": "2015-03-24T00:00:00",
"description": "ALogs",
"notes": "",
"lastUpdateDate": "2015-03-24T14:06:42.063",
"location": "BOX A001",
"metadata": { }
},
{
"id": 100039813,
"group": {
"code": "DD",
"description": "Delivery Documents"
},
"type": {
"code": "BL",
"description": "Logbooks"
},
"reference": "BALB",
"date": "2015-03-24T00:00:00",
"description": "Logbooks",
"notes": "",
"lastUpdateDate": "2015-03-24T14:07:42.44",
"location": "BOX A001",
"metadata": { }
}
]
}
How can I De-serialize following json?
{
"data": {
"11396": {
"description": "Timer project",
"status": "ACTIVE",
"customer": {
"locations": {},
"id": 96626
},
"tasks": [
{
"description": "Timer Task",
"unit": "h",
"vatPct": 0.2,
"unitPrice": 12,
"billable": true,
"id": 19660
}
],
"price": 0,
"pricing": "UNIT",
"allowProducts": true,
"hasUninvoicedItems": false,
"id": 11396
},
"11397": {
"description": "Timer Project 2",
"status": "ACTIVE",
"customer": {
"locations": {},
"id": 96626
},
"tasks": [
{
"description": "Timer Task2",
"unit": "h",
"vatPct": 0.05,
"unitPrice": 20,
"billable": true,
"id": 19655
}
],
"price": 0,
"pricing": "UNIT",
"allowProducts": true,
"hasUninvoicedItems": false,
"id": 11397
}
},
"ok": true
}
The problem is that values 11396, 11397 as class name (if convert to c#) which are actually ids of that particular record. so when converting this json to c# using http://json2csharp.com. it shows as this
public class Locations
{
}
public class Customer
{
public Locations locations { get; set; }
public int id { get; set; }
}
public class Task
{
public string description { get; set; }
public string unit { get; set; }
public double vatPct { get; set; }
public double unitPrice { get; set; }
public bool billable { get; set; }
public int id { get; set; }
}
public class __invalid_type__11397
{
public string description { get; set; }
public string status { get; set; }
public Customer customer { get; set; }
public List<Task> tasks { get; set; }
public double price { get; set; }
public string pricing { get; set; }
public bool allowProducts { get; set; }
public bool hasUninvoicedItems { get; set; }
public int id { get; set; }
}
public class Locations2
{
}
public class Customer2
{
public Locations2 locations { get; set; }
public int id { get; set; }
}
public class Task2
{
public string description { get; set; }
public string unit { get; set; }
public double vatPct { get; set; }
public double unitPrice { get; set; }
public bool billable { get; set; }
public int id { get; set; }
}
public class __invalid_type__11396
{
public string description { get; set; }
public string status { get; set; }
public Customer2 customer { get; set; }
public List<Task2> tasks { get; set; }
public double price { get; set; }
public string pricing { get; set; }
public bool allowProducts { get; set; }
public bool hasUninvoicedItems { get; set; }
public int id { get; set; }
}
public class Data
{
public __invalid_type__11397 __invalid_name__11397 { get; set; }
public __invalid_type__11396 __invalid_name__11396 { get; set; }
}
public class RootObject
{
public Data data { get; set; }
public bool ok { get; set; }
}
any help is much appreciated.
I resolved this issue by parsing the json string to JTOKEN and the querying the required data.
This was possible because my datas inside json was static
JToken token = JObject.Parse(response);
var justDaily = token["data"];
ProjectList = new List<Project>();
foreach (JToken child in justDaily.Children())
{
foreach (JToken grandChild in child)
{
Project temp = JsonConvert.DeserializeObject<Project>(grandChild.ToString().Replace("\r\n", ""));
ProjectList.Add(temp);
}
}
Hope this will help someone else also
Initially my json was in the format,
"code": 0,
"message": "success",
"students": [
{
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good",
},
{
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad",
}]
And so i used the following class for deserializing using Newtonsoft.json
[DataContract]
public class students
{
[DataMember(Name = "code")]
public int Code { get; set; }
[DataMember(Name = "message")]
public string Message { get; set; }
[DataMember(Name = "students")]
public StudentDetail StudentDetail { get; set; }
}
[DataContract]
public class StudentDetail
{
[DataMember(Name = "id")]
public string ID { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "percentage")]
public double PercentageForEdit { get; set; }
[DataMember(Name = "type")]
public string Type { get; set; }
}
But now my json is changed to,
"code": 0,
"message": "success",
"students": {
"details":{
"hjeke": {
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good",
},
"Second": {
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad",
}
}
}
How should i change my students class so that,
StudentDetails = JsonConvert.DeserializeObject<Students>(data);
If you using Newtonsoft.Json, try to use that classes:
public class StudentDetails
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
public class Student
{
public int code { get; set; }
public string message { get; set; }
public List<StudentDetails> students { get; set; }
}
After that, you can use that class to Deserialize responses using following way:
var parsedResponse = JsonConvert.DeserializeObject<Student>(data);
P.S. Of course, do not forget about [DataContract] and [DataMember] attributes
first of all your Json does not seem to be valid, the surrounding brackets are missing for the object { }.
To find your matching C# class there is a nice converter on this site
For your second Json with the object brackets:
"code": 0,
"message": "success",
"students": {
"details":{
"hjeke": {
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good",
},
"Second": {
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad",
}
}
}
it suggests these classes:
public class Hjeke
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
public class Second
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
public class Details
{
public Hjeke hjeke { get; set; }
public Second Second { get; set; }
}
public class Students
{
public Details details { get; set; }
}
public class RootObject
{
public int code { get; set; }
public string message { get; set; }
public Students students { get; set; }
}
You can play around with this generator tool by yourself.