JSON with array structure [duplicate] - c#

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.

Related

How to display JSON data (nested) in C#

I am fetching an API that returns a JSON response like this:
{
"id": 161635,
"rev": 1,
"fields": {
"System.Url": "http://google.com",
"System.Type": "Bug",
"System.State": "New",
"System.AssignedTo": {
"displayName": "John Doe"
}
}
}
I want to display the id and everything inside fields.
This is my model:
public class WorkItemDetail {
public int id { get; set; }
public Dictionary<string, object> fields {get;set;}
}
Here is the problem, I can display the id and everything in fields except for some reason, I can't show displayName
Here is what I doing:
#WorkItemDetailResponse.id
#WorkItemDetailResponse.fields["System.WorkItemType"];
#WorkItemDetailResponse.fields["System.State"];
#WorkItemDetailResponse.fields["System.AssignedTo"];
#WorkItemDetailResponse.fields["System.AssignedTo"]["displayName"]; <!-- does not work -->
#code{
WorkItemDetailResponse = JsonConvert.DeserializeObject<WorkItemDetail>(ResponseBody);
}
I am new to C# so I don't know why this line is not working
#WorkItemDetailResponse.fields["System.AssignedTo"]["displayName"]
Create your DTO structure as follows:
public class Fields
{
[JsonProperty("System.Url")]
public string SystemUrl { get; set; }
[JsonProperty("System.Type")]
public string SystemType { get; set; }
[JsonProperty("System.State")]
public string SystemState { get; set; }
[JsonProperty("System.AssignedTo")]
public SystemAssignedTo SystemAssignedTo { get; set; }
}
public class WorkItemDetail
{
public int id { get; set; }
public int rev { get; set; }
public Fields fields { get; set; }
}
public class SystemAssignedTo
{
public string displayName { get; set; }
}
here's fiddle: https://dotnetfiddle.net/F9Wppv
another way - using dynamic variable: https://dotnetfiddle.net/Goh7YY
You need to cast the object value to a JObject
((JObject)JsonConvert.DeserializeObject<WorkItemDetail>(json).fields["System.AssignedTo"])["displayName"]
JSON.Net will create a JObject if the property type is object and the value is a JSON object.
db<>fiddle

How can I get specific values from JObject in c# [duplicate]

This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 4 years ago.
I need to retrieve specific values from API response. My response looks like one below. How can I access to [productCodeScheme] value of each pack?
dynamic api = JObject.Parse(response.Content);
// api contains
{
"operationCode": "12200000",
"packs": [
{
"pack": {
"productCodeScheme": "ppn",
"productCode": "15000436574634",
"serialNumber": "0000000001",
"batchId": "00001",
"expiryDate": "201201"
},
"result": {
"operationCode": "61020008",
"warning": "The product code is invalid."
}
},
{
"pack": {
"productCodeScheme": "gs1",
"productCode": "15000436574634",
"serialNumber": "0000000002",
"batchId": "00001",
"expiryDate": "201201"
},
"result": {
"operationCode": "11310300",
"information": "The pack has been marked as stolen.",
"state": "Stolen"
}
}
]
}
If you want your object to stay dynamic, you could just do
dynamic result = JsonConvert.DeserializeObject<dynamic>(response.Content);
after, you can access the objects inside like below:
foreach(dynamic item in result.packs)
{
string productCodeScheme = item.pack.productCodeScheme.ToString();
}
However, i would strongly suggest that you to deserialize your JSON responses into defined objects instead of using dynamic. dynamics are both insecure and inefficient. You can do someting like example below,
public class PackDetails
{
public string productCodeScheme { get; set; }
public string productCode { get; set; }
public string serialNumber { get; set; }
public string batchId { get; set; }
public string expiryDate { get; set; }
}
public class Result
{
public string operationCode { get; set; }
public string warning { get; set; }
public string information { get; set; }
public string state { get; set; }
}
public class Pack
{
public PackDetails pack { get; set; }
public Result result { get; set; }
}
public class ResponseObject
{
public string operationCode { get; set; }
public List<Pack> packs { get; set; }
}
then you can deserialize a ResponseObject like below and use it
var responseObject = JsonConvert.DeserializeObject<ResponseObject>();
foreach(PackDetails item in responseObject.packs)
{
string productCodeScheme = item.pack.productCodeScheme;
}

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {“name”:“value”})

I have JSON returning in the following format:
{
"Items": [
{
"unique_id": "11111111111",
"rages": {
"rage_content": "Hello rage 2",
"date_stamp": "21/07/2017",
"id": 2
}
},
{
"unique_id": "2222222222",
"rages": {
"rage_content": "Hello rage 1",
"date_stamp": "21/07/2017",
"id": 1
}
}
],
"Count": 2,
"ScannedCount": 2
}
And I have the following 2 classes defined:
Items.cs:
namespace ragevent_A0._0._1
{
class Items
{
public String rage_id { get; set; }
public rage rage { get; set; }
}
}
rage.cs:
class rage
{
public String rage_content { get; set; }
public String date_stamp { get; set; }
public int id { get; set; }
}
I am using the following code in order to attempt to deseralize the JSON returned above:
List<Items> data = JsonConvert.DeserializeObject<List<Items>>(json);
However, I am not able to successfully deserialize the data due to the above error. I have tried a few solutions online, however I have not managed to find a solution which works with the format of my returned JSON. I have used a JSON formatter and it is formatted correctly, so that shouldn't be the issue.
Any help would be much appreciated!
For the posted JSON data below should be the model you need (credit: http://json2csharp.com/). There is mismatch between the property name rage_id. You can use JsonProperty attribute
public class Rages
{
public string rage_content { get; set; }
public string date_stamp { get; set; }
public int id { get; set; }
}
public class Item
{
[JsonProperty(Name="rage_id")]
public string unique_id { get; set; }
public Rages rages { get; set; }
}
public class RootObject
{
public List<Item> Items { get; set; }
public int Count { get; set; }
public int ScannedCount { get; set; }
}
Your deserialization should be
var data = JsonConvert.DeserializeObject<RootObject>(json);

json file read from c# code [duplicate]

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

WCF writing Nested Json Webservice

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.

Categories

Resources