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);
Related
How can I deserialize JSON to a list using DeserializeObject and JsonProperty while the indexes of the elements are non-integer?
JSON:
{
"success": true,
"TEST": {
"360450323_188530139": {
"id": "24216",
"name": "zxc",
"desc": "cxz"
},
"310777518_0": {
"id": "6458678634",
"name": "dfgsfd",
"desc": "sdfxcvnbhr"
}
}
}
Is there any way to make a list from that?
I've tried:
using(WebClient wc = new WebClient())
{
var url = "...";
var json = wc.DownloadString(url);
Result result = JsonConvert.DeserializeObject<Result>(json);
}
public class Result
{
[JsonProperty("success")]
public string Success { get; set; }
[JsonProperty("TEST")]
public List<Test> Tests{ get; set; }
}
public class Test
{
[JsonProperty("id")]
public int id { get; set;}
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("desc")]
public string Desc { get; set; }
}
You have a keyed collection in the JSON, which maps easily to a dictionary. You could examine result.Test.Values
using(WebClient wc = new WebClient())
{
var url = "...";
var json = wc.DownloadString(url);
Result result = JsonConvert.DeserializeObject<Result>(json);
// result.Values should contain the Test instances at this point.
}
public class Result
{
[JsonProperty("success")]
public string Success { get; set; }
[JsonProperty("TEST")]
public Dictionary<string,Test> Tests{ get; set; }
}
public class Test
{
// omitted - same as in question.
}
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; }
}
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; }
}
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);
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"}]