Deserialize Json Property's Property to Property - c#

In json.net, how can I deserialize this json:
{
"items": {
"count": 1,
"data": [
{
...
},
...
],
}
}
To this C# class:
class MyData
{
[JsonProperty("items/data")] // this doesn't work
public List<object> Items { get; set; }
}
-
// Then this doesn't populate Items
MyData data = JsonConvert.DeserializeObject<MyData>(json);
Is there an elegant way of doing this with json.net?

I just thought of how I could do this:
var jObject = JObject.Parse(json);
jObject["items"] = jObject["items"]["data"];
MyData data = JsonConvert.DeserializeObject<MyData>(jObject.ToString());
Anyone have a better solution?

For populate items you should have this
public class Datum
{
}
public class Items
{
public int count { get; set; }
public List<Datum> data { get; set; }
}
public class RootObject
{
public Items items { get; set; }
}
and then use this:
MyData data = JsonConvert.DeserializeObject<RootObject>(json);

Related

Retrieve data from json string in c#

I am new for json , as i am getting following json string.
i need following output 1,2,6,3,5,4 (get id object with comma separated) in asp.net with c#
[
{
"id":1,
"children":
[
{
"id":2,
"children" :
[
{"id":6},
{"id":3},
]
}
]
},
{
"id":5
},
{
"id":4
}
]
Code Behind work :
public class GetId
{
public string id { get; set; }
}
List<GetId> myDeserializedObjList = (List<GetId>)Newtonsoft.Json.JsonConvert.DeserializeObject(nestable_list_1_output.InnerText, typeof(List<GetId>));
for(int i=0; i < myDeserializedObjList.Count;i++)
{
string Id = myDeserializedObjList[i].id.ToString();
}
after implement this i get only 1,5,4 ...also i want children object Ids..
Thanks
Json to c# converters will not work great with this recursive definitions. In fact your class is simple
public class ID
{
public int id { get; set; }
public List<ID> children { get; set; }
}
Your json can now be in any depth. All you have to do is
var myDeserializedObjList = JsonConvert.DeserializeObject<List<ID>>(json);
You can now get the results recursively
PrintMyObject(myDeserializedObjList);
void PrintMyObject(List<ID> ids)
{
foreach (var id in ids)
{
Console.WriteLine(id.id);
if (id.children != null)
PrintMyObject(id.children);
}
}
To make the answer complete: This part is a Linq trick, to flatten your recursive data structure.
Func<List<ID>, IEnumerable<ID>> flattenList = null;
flattenList = l => l.SelectMany(x => new[] { x }.Concat( x.children==null
? Enumerable.Empty<ID>()
: flattenList(x.children)));
var flatList = flattenList(myDeserializedObjList).ToList();
Use json2csharp to generate correct class structure -
public class Child2
{
public int id { get; set; }
}
public class Child
{
public int id { get; set; }
public List<Child2> children { get; set; }
}
public class RootObject
{
public int id { get; set; }
public List<Child> children { get; set; }
}
Use this class RootObject to deserialize json response.
You should include children in your definition of the GetId class.
public class GetId
{
public int id { get; set; }
public List<GetId> children { get; set; }
}
Then when collecting the id's, you do it using a recursive call to make sure you get all ids in the lower structures.
private void CollectIdValues(List<GetId> list, List<int> ids){
foreach(GetId item in list){
ids.Add(item.id);
if(item.children != null){
CollectIdValues(item.children, ids);
}
}
}
List<GetId> myDeserializedObjList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<GetId>>(jsonString));
List<int> allIds = new List<int>();
CollectIdValues(myDeserializedObjList, allIds);

Can't deserialize with JavaScriptSerializer

I have this JSON file:
{
"result":
[
{
"desc" : "Ok",
"cod" : "1"
}
],
"data":
[
{
"cod" : "95B86DF6AE282E67B6B7437D09570847"
}
]
}
A method which deserializes it
protected void Deserialize()
{
string path = AppDomain.CurrentDomain.BaseDirectory + #"\token.json";
string file = System.IO.File.ReadAllText(path);
var deserializer = new JavaScriptSerializer();
var results = deserializer.Deserialize<data>(file);
}
public class result
{
public int cod { get; set; }
public string desc{ get; set; }
}
public class data
{
public string cod{ get; set; }
}
The problem is that it doesn't deserialize it, and creates empty Data object.
I'm missing something but I don't know what, hope someone will help me.
Your data model does not correspond to the JSON object, and the serializer is not able to deserialize it properly. Notice that inside that object you have arrays of objects, so the correct structure you need to deserialize that would be something like:
public class Token
{
public Result[] result { get; set; }
public Data[] data { get; set; }
}
And then you can do:
var res = JsonConvert.DeserializeObject<Token>(file);

Deserialize JSON C# Json.net [duplicate]

This question already has answers here:
How can I parse a JSON string that would cause illegal C# identifiers?
(3 answers)
Closed 8 years ago.
I am trying to deserialize a Json response from an API.
The data looks like this
{
"response": {
"6112": {
"ID": 6112,
"Title": "AdditionalPhotos"
},
"5982": {
"ID": 5982,
"Title": "BikeRide"
},
"total_records": "20",
"returned_count": 10,
"returned_records": "1-10"
}
}
C# class:
public class Products
{
public class Product
{
public string Id { get; set; }
public string Title { get; set; }
}
public Product product { get; set; }
}
public class ss
{
public Dictionary<string, Products.Product> Response { get; set; }
public string total_records { get; set; }
}
Serialization code
ss res = Newtonsoft.Json.JsonConvert.DeserializeObject<ss>(jsonData());
I can get it to work without the total_records entry and below by deserializng to a Dictionary <string , Product>. But I cannot figure out how to get it to work. This is the error I get
Error converting value "20" to type 'Products+Product'. Path 'response.total_records'
I know why I get the error, but I'm unsure how I can proceed without going in and substringing from total_records down. I have no control over the API data.
Edit: you guys are fast, I was still getting to putting the classes up
First you json is not valid one, it should look like this
{
"response":{
"6112":{
"ID":"6112",
"Title":"Additional Photos",
},
"5982":{
"ID":"5982",
"Title":"Bike Ride",
},
"total_records": "20",
"returned_count": "10",
"returned_records": "1-10",
}
}
If you mean the response to contain list it should look like this
{
"response":{
"myArray": [
{
"ID":"6112",
"Title":"Additional Photos",
},
{
"ID":"5982",
"Title":"Bike Ride",
}
],
"total_records": "20",
"returned_count": "10",
"returned_records": "1-10",
}
}
So your code look like this
public class MyArray
{
public string ID { get; set; }
public string Title { get; set; }
}
public class Response
{
public List<MyArray> myArray { get; set; }
public string total_records { get; set; }
public string returned_count { get; set; }
public string returned_records { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}
If you have control over API response then please refer to Mzf's answer.
If you don't have control over API then it may not be possible to do this particular deserialization on one go. You might have to loop.
Here's my take.
Update
Modified my approach:
Created a class Response which inherits from Dictionary<string, Product>, and added the metadata parts like total_records, records_count to it's public properties. And created a JsonConverter that can deserialize JObject to Response class.
The logic used for deserialization is quite simple:
Extract the metadata parts like total_records, records_count to variables.
Then remove those metadata from the JObject, so that the key values becomes homogeneous.
Now Json.net will be easily able to serialize JObject to Response object, as key values are homogenous.
Assign the metadata extracted previously to the properties of Response object
public void Deserialize()
{
var json = #"{
'response':{
'6112':{
'ID':6112,
'Title':'Additional Photos',
},
'5982':{
'ID':5982,
'Title':'Bike Ride',
},
'total_records': '20',
'returned_count': 10,
'returned_records': '1-10',
}
}";
var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject<ss>(json, new ResponseConverter());
}
public class Response : Dictionary<string, Product>
{
public int total_records { get; set; }
public int returned_count { get; set; }
public string returned_records { get; set; }
}
public class Product
{
public string Id { get; set; }
public string Title { get; set; }
}
public class ss
{
public Response Response { get; set; }
}
public class ResponseConverter : Newtonsoft.Json.JsonConverter
{
private Response CreateResponse(Newtonsoft.Json.Linq.JObject jObject)
{
//preserve metadata values into variables
int total_records = jObject["total_records"].ToObject<int>();
var returned_records = jObject["returned_records"].ToObject<string>();
var returned_count = jObject["returned_count"].ToObject<int>();
//remove the unwanted keys
jObject.Remove("total_records");
jObject.Remove("returned_records");
jObject.Remove("returned_count");
//once, the metadata keys are removed, json.net will be able to deserialize without problem
var response = jObject.ToObject<Response>();
//Assign back the metadata to response object
response.total_records = total_records;
response.returned_count = returned_count;
response.returned_records = returned_records;
//.. now person can be accessed like response['6112'], and
// metadata can be accessed like response.total_records
return response;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Response);
}
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
var jObject = Newtonsoft.Json.Linq.JObject.Load(reader);
Response target = CreateResponse(jObject);
serializer.Populate(jObject.CreateReader(), target);
return target;
}
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
In my opinion this is how the JSON file should look like:
{
"response": {
"5982": {
"ID": 5982,
"Title": "BikeRide"
},
"6112": {
"ID": 6112,
"Title": "AdditionalPhotos"
},
"total_records": "20",
"returned_count": 10,
"returned_records": "1-10"
}
}
and this is how the class should look like
public class __invalid_type__5982
{
public int ID { get; set; }
public string Title { get; set; }
}
public class __invalid_type__6112
{
public int ID { get; set; }
public string Title { get; set; }
}
public class Response
{
public __invalid_type__5982 __invalid_name__5982 { get; set; }
public __invalid_type__6112 __invalid_name__6112 { get; set; }
public string total_records { get; set; }
public int returned_count { get; set; }
public string returned_records { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}

Deserialize JSON with JSON.NET issues

I've been trying to de-serialize a JSON stream in C# using JSON.Net
I have a JObject 'JO1' and when I do a JO1.ToString() on that the string contents are:
{
"Successful": true,
"Value": [
{
"no": "1",
"name": "Accounting"
},
{
"no": "2",
"name": "Marketing"
},
{
"no": "3",
"name": "Information Technology"
}
]
}
I have tried the following .NET code to no avail.
public class main()
{
public void main()
{
JObject jo = new JObject();
jo = functionthatretrievestheJSONdata();
List<departments> dt1 = JsonConvert.DeserializeObject<List<departments>>(jo.ToString());
}
}
public class departments
{
public int no { get; set; }
public string name { get; set; }
}
Can someone please give me a pointer in the right direction?
You're going to need a class to wrap List<departments>, like this:
public class DeserializedDepartments
{
public bool Successful { get; set; }
public List<departments> Value { get; set; }
}
and so you'd deserialize like this:
DeserializedDepartments dt1 =
JsonConvert.DeserializeObject<DeserializedDepartments>(jo.ToString());
Now your List<departments> is in the Value of dt1; or dt1.Value.
You are not taking into account that the list is an array attached to another object.
you have an object with a boolean value called Successful and an array of Departments called Value.
Try this:
public class main()
{
public void main()
{
JObject jo = new JObject();
jo = functionthatretrievestheJSONdata();
Results dt1 = JsonConvert.DeserializeObject<Results>(jo.ToString());
var depts = dt1.Value;
}
}
public class Results
{
public bool Successful {get;set;}
public List<Department> Value {get;set;}
}
public class Department
{
public int no { get; set; }
public string name { get; set; }
}

How to filter only array from JSON

My JSON string is as follows,
{
"Data":[
{
"id":"1",
"Name":"Sachin"
},
{
"id":"2",
"Name":"Rahul"
},
{
"id":"3",
"Name":"Sovrav"
}
]
}
Now, I want to filter only array from that JSON string and store them in another variable the result should be like this
[
{
"id":"1",
"Name":"Sachin"
},
{
"id":"2",
"Name":"Rahul"
},
{
"id":"3",
"Name":"Sovrav"
}
]
Please help me
Have you looked into Newtonsoft.JSon - Nuget Package Link?
Following Newtonsoft you could do this:
Create a model to Deserialize your JSON
public class DataJson {
List<PersonJson> Data { get; set; }
}
public class PersonJson {
public int id { get; set; }
public string Name { get; set; }
}
Deserialize your Json object easily:
JsonConvert.DeserializeObject(json);
For a similar question you could look here: Deserializing JSON Object Array with Json.net
Some keywords for searching more information would be: Deserialize, Json, C#
Use Json.NET and deserialize object and serialize only list.
public class Datum
{
public string id { get; set; }
public string Name { get; set; }
}
public class RootObject
{
public List<Datum> Data { get; set; }
}
static void Main()
{
string json = "{ \"Data\":[ { \"id\":\"1\", \"Name\":\"Sachin\" }, { \"id\":\"2\", \"Name\":\"Rahul\" }, { \"id\":\"3\", \"Name\":\"Sovrav\" } ] }";
RootObject ro = JsonConvert.DeserializeObject<RootObject>(json);
string newJson = JsonConvert.SerializeObject(ro.Data);
}
And newJson contains:
[{"id":"1","Name":"Sachin"},{"id":"2","Name":"Rahul"},{"id":"3","Name":"Sovrav"}]

Categories

Resources