WCF writing Nested Json Webservice - c#

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.

Related

JSON with array structure [duplicate]

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.

Custom JSON Serialize with custom mapping C#

I want to serialize/deserialize the following JSON:
{
"result": {
"ID": 1,
"TITLE": "Example",
"ARRAY": [
{
"Item1": "Result1",
"Item2": "Result2"
}
]
}
}
I tried with the following class format, but no sucess yet... Can someone help me deserialize it?
public class myClass
{
public string ID { get; set; }
[JsonProperty("TITLE")]
public string Name { get; set; }
}
obs.: Using the namespace Newtonsoft.JSON
In your example class definition above, you have called the class myClass but you would have had to call it result because ID and TITLE are members of the result JSON in the given example. myClass would not resolve to anything.
I don't know why you'd want to have a property called Name that is mapped to TITLE, but ok, if you want to do that you can modify the solution after you get it working.
Still, we're not done yet. You also have a JSON member called ARRAY and you need to define a separate class for that.
And still there is an additional problem: the result JSON is nested inside an implicit base object, so we need to define that as well. Let's call it BaseResult.
public class ARRAY
{
public string Item1 { get; set; }
public string Item2 { get; set; }
}
public class Result
{
public int ID { get; set; }
public string TITLE { get; set; }
public List<ARRAY> ARRAY { get; set; }
}
public class BaseResult
{
public Result result { get; set; }
}
If you are using Visual Studio, you can copy your JSON and paste it in any *.cs file with Edit > Paste Special > Paste JSON as Classes. It will generate POCO objects representing your JSON, which in your case will be this:
public class Rootobject
{
public Result result { get; set; }
}
public class Result
{
public int ID { get; set; }
public string TITLE { get; set; }
public ARRAY[] ARRAY { get; set; }
}
public class ARRAY
{
public string Item1 { get; set; }
public string Item2 { get; set; }
}
Then, asuming that you have your JSON in a string variable named data, you can deserialize it as follows:
var result= JsonConvert.DeserializeObject<Rootobject>(data);

Json Deserializing to null using Newtosoft Json

I have the following json:
{
"cuisines": [
{
"cuisine": {
"cuisine_id": 152,
"cuisine_name": "African"
}
},
{
"cuisine": {
"cuisine_id": 1,
"cuisine_name": "American"
}
},
{
"cuisine": {
"cuisine_id": 4,
"cuisine_name": "Arabian"
}
},
{
"cuisine": {
"cuisine_id": 151,
"cuisine_name": "Argentine"
}
}
]
}
Im using RestSharp to get the data and sending it to JSON.Net:
JsonConvert.DeserializeObject<Cuisines>(content)
And I'm using the following classes:
public class Cuisine
{
[JsonProperty("cuisine_id")]
public string cuisine_id { get; set; }
[JsonProperty("cuisine_name")]
public string cuisine_name { get; set; }
}
public class Cuisines
{
[JsonProperty("cuisines")]
public List<Cuisine> AllCuisines { get; set; }
}
What is wierd is, the return data is finding 81 cuisine objects on my request, but all the Cuisine info is null.
You model needs one more class. So it should be
public class Cuisine
{
[JsonProperty("cuisine_id")]
public string cuisine_id { get; set; }
[JsonProperty("cuisine_name")]
public string cuisine_name { get; set; }
}
public class CuisineWrapper
{
public Cuisine cuisine { get; set; }
}
public class Cuisines
{
[JsonProperty("cuisines")]
public List<CuisineWrapper> AllCuisines { get; set; }
}
Your classes definitions doesn't match provided JSON. Top level array contains objects with a single property (object) cuisine, like so:
"cuisine": {
"cuisine_id": 152,
"cuisine_name": "African"
}
where as your C# List<Cuisine> contains objects directly exposing cuisine_id and cuisine_name. If you can't change JSON, decorate class Cuisine with JsonObjectAttribute
You actually have 3 objects - A root object that contains a property named cuisines that is a collection of Cuisine.
When you paste your JSON as classes in visual studio you get the following structure (which you would probably want to rename some things and list-ify the array)
public class Rootobject
{
public Cuisine[] cuisines { get; set; }
}
public class Cuisine
{
public Cuisine1 cuisine { get; set; }
}
public class Cuisine1
{
public int cuisine_id { get; set; }
public string cuisine_name { get; set; }
}
Your JSON is nested more than your class structure. If you can change your JSON to the form:
"cuisines": [
{
"cuisine_id": 152,
"cuisine_name": "African"
},
{
"cuisine_id": 1,
"cuisine_name": "American"
},
.. etc
Then it will match your class structure.
Alternatively, change your class structure to match the JSON:
public class Cuisine
{
[JsonProperty("cuisine")]
public CuisineData data { get; set; }
}
public class CuisineData
{
[JsonProperty("cuisine_id")]
public string cuisine_id { get; set; }
[JsonProperty("cuisine_name")]
public string cuisine_name { get; set; }
}
public class Cuisines
{
[JsonProperty("cuisines")]
public List<Cuisine> AllCuisines { get; set; }
}

JSon.NET deserialising subitems

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.

How to create c# class for below format JSON

Could someone help me in structuring the class for below format JSON.
I have already tried http://json2csharp.com/ tool. It did not work as my list of people are dynamic, i.e. values 123, 124 etc are not pre-defined.
{
"people":
{
"123":"jack henry",
"124":"john henry",
"125":"jill henry",
"215":"jim henry",
...
}
}
public class Root
{
public Dictionary<string, string> people = new Dictionary<string,string>();
}
Using Json.NET:
Root root = new Root();
root.people.Add("123", "jack henry");
//... Add more people
string json = JsonConvert.SerializeObject(root);
Visual Studio > Edit > Paste Special > Paste JSON as classes
public class Rootobject
{
public People people { get; set; }
}
public class People
{
public string _123 { get; set; }
public string _124 { get; set; }
public string _125 { get; set; }
public string _215 { get; set; }
}
You already got an answer for your question. But, looking at the sample JSON looks like you are actually storing a list of persons. If that is the case, you might create classes like this
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class People
{
public List<Person> Persons { get; set; }
//other properties
}
And have your JSON standardized as
{
"Persons": [
{
"Id": 123,
"Name": "Jack"
},
{
"Id": 124,
"Name": "John"
}
]
}
Which will be much more meaningful and readable (by code and human).
Source: http://json2csharp.com/
public class People
{
public string __invalid_name__123 { get; set; }
public string __invalid_name__124 { get; set; }
public string __invalid_name__125 { get; set; }
public string __invalid_name__215 { get; set; }
}
public class RootObject
{
public People people { get; set; }
}

Categories

Resources