How to deserialize multiple object within an object? - c#

I have the following JSON which I'm trying to deserialize.
"objects": {
"1612": {
"id": 1612
},
"1626": {
"id": 1626
}
}
I'm trying to deserialize this into a list ideally but I haven't had any luck so far.
I've tried the following:
public List<Object> objects { get; set; }
public Dictionary<string, Team> objects { get; set; }
I know that ideally the JSON should be inside an array [], but it isn't.
Thank you in advance.

Your JSON does not contain any collections, so a list/array would not be appropriate.
You should have a parent object with one property objects:
public class RootObject
{
// I dont know what Team is but I assume it has the 'id' property
public Dictionary<string, Team> Objects { get; set; }
}
If you are using Json.NET then the deserialization would be:
var rootObj = JsonConvert.DeserializeObject<RootObject>(someJson);
Fiddle here

Related

Is it possible to deserialize JSON with an unknown parameter name without using a custom converter?

I apologize if this is a duplicate, but none of the related answers I saw had JSON similar to the format I'm dealing with. I'm consuming an API response that has the following JSON format:
{
"KnownPropName": [
{
"DynamicPropName": [
{
"KnownProp1": "value",
"KnownProp2": "value"
},
{
"KnownProp1": "value",
"KnownProp2": "value"
}]
}]
}
I know the names of the parameters for each object except for "DynamicPropName", which I cannot know ahead of time.
I have the below classes setup:
private class TestResponse
{
public TestOuter[] KnownPropName { get; set; }
}
private class TestOuter
{
public TestInner[] TestInners { get; set; }
}
private class TestInner
{
public string KnownProp1 { get; set; }
public string KnownProp2 { get; set; }
}
If I change the property name "TestInners" to "DynamicPropName" everything deserializes with no issues. However, since I will not know the actual property name ahead of time I need to somehow have this work when "TestInners" does not match the corresponding property name.
I don't believe I can use a dictionary because the arrays don't contain string keys, but instead objects.
I know I can use a custom converter to solve this, but I'd like to know if it is at all possible without using one. Is there a way to have JSON deserialize based on the order of the parameters instead of depending on the name?
From the JSON sample you've given, I don't see why a dictionary wouldn't work here. As I see it, KnownPropName is actually an array of dictionaries where each dictionary has string keys, representing the dynamic property name(s), and values which are arrays of TestInner objects.
In other words, declare your classes like this:
private class TestResponse
{
public Dictionary<string, TestInner[]>[] KnownPropName { get; set; }
}
private class TestInner
{
public string KnownProp1 { get; set; }
public string KnownProp2 { get; set; }
}
You don't need the TestOuter class.
Fiddle: https://dotnetfiddle.net/MHOYwm

How to Deserialize JSON data? C#

Im getting a Json Data from an API and i have been trying to deserialize.
Json data:
{
   "items": [
      {
         "id": "1",
         "name": "samplename",
         "AddressList1": {
            "City": "Hyd",
            "State": "TN",
            "Country": "IN"
         },
         "Age": "10"
      },
      {
         "id": "2",
         "name": "samplename2",
         "AddressList1": {
            "City": "Hydd",
            "State": "TN",
            "Country": "IN"
         },
         "Age": "10"
      }
   ],
   "paging": {
      "cursors": {}
   }
}
Entities:
public class AddressList1
{
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
public class Item
{
public string id { get; set; }
public string name { get; set; }
public AddressList1 addressList1 { get; set; }
public string Age { get; set; }
}
public class Cursors
{
}
public class Paging
{
public Cursors cursors { get; set; }
}
public class Users
{
public List<Item> items { get; set; }
public Paging paging { get; set; }
}
C# code:
JsonConvert.DeserializeObject<List<Users>>(content);
Error Message:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[Entities.Users]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly.
where am i doing wrong?
The following is a JSON-object; in your case a User
{ ... }
The following is a JSON-array; in your case an array of User
[ { ... }, { ... } ]
Thus if you want to deserialize the JSON you got into an array of Users this is not possible because you have no array in JSON.
Therefore the right code to deserialize is:
JsonConvert.DeserializeObject<Users>(content);
Furthermore your mapping is erroneous because in JSON there is a property AddressList1 and in the class it is called addressList1
Given your JSON, you would need a POCO object that contains a items member and a paging member.
JsonConvert.DeserializeObject<Users>(content);
should work.
Your Json string is good formatted and the entities are according to Json2Csharp good too.
but your problem is with the instruction JsonConvert.DeserializeObject<List<Users>>(content);
all that json that you have is only ONE User, and you are trying to get a list of them, there is the issue,
you can try instead with:
JsonConvert.DeserializeObject<Users>(content);
Try Below Code
JsonConvert.DeserializeObject<Users>(content);
Your entities(models) look just fine. If you are using, or were to use ASP.NET Web API 2, and your client is using the http verb post for example, this setup would work as Web API takes care of the object deserialization:
public HttpStatusCode Post(Item item)
{
Debug.Write(item.toString());
return HttpStatusCode.OK;
}
If you insist in deserializing manually then use the JavaScriptSerializer library which allows you to do things like:
Item item = new JavaScriptSerializer().Deserialize<Item>(content);
Notice that .Deserialize<T>() takes a generic which in your case it Item.
Hope that helps.

How to parse json with different key names and similar objects in each key?

I have this JSON :
{
"response": {
"PEOPLE": {
"PERSON1": {
"name": "jon",
"last": "jony"
},
"PERSON2": {
"name": "mike",
"last": "mikey"
}
}
}
}
How can I parse it to a dictionary which the key will be the PERSONX string?
I'm new to c#, and know that in Java I need to have one class, where internal key will be : "person_name"...
I suggest create a class because it's easier to work and you have full control of it.
public class Response
{
public Dictionary<string,Person> People{ get; set; }
}
public class Person
{
public string Name { get; set; }
public string Last { get; set; }
}
When properties have different names I use Dictionary and then you can use LINQ to access them.
Get value of a dictionary:
var valueOfFirstPeopleElement = People.FirstOrDefault().Value;
This way you have the person class.
In order to parse the json to this class you must deserialize using a json converter.
Response response = JsonConvert.DeserializeObject<Response>(jsonData);
To do the reverse you Serialize instead.
string jsonData = JsonConvert.SerializeObject(response);

Deserializing an array of objects with Json.Net

The received data is like this:
Inside each item, there is an object, customer, I have an identical class for that. How can I convert them using Json.net?
I have tried the followings:
var data = JsonConvert.DeserializeObject<List<customer>>(val);
and adding another class:
public class customerJson
{
public Customer customer{ get; set; }
}
And trying to deserialize it:
var data = JsonConvert.DeserializeObject<List<customerJson>>(val);
With both of them I get an exception:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[customer]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'rows', line 1, position 8.
Data:
{"rows":[{"id":"232333","name":"nam"},{"id":"3434444","name":"2ndName"}]}
If I read your json data structure correctly you would want this:
public class Root
{
public List<Customer> rows { get; set; }
}
and
var data = JsonConvert.DeserializeObject<Root>(val);
Tested code:
void Main()
{
var test = JsonConvert.DeserializeObject<Root>("{\"rows\":[{\"id\":\"232333\",\"name\":\"nam\"},{\"id\":\"3434444\",\"name\":\"2ndName\"}]}");
Console.WriteLine(test.rows[0].id); // prints 232333
}
public class Customer
{
public int id { get; set; }
}
public class Root
{
public List<Customer> rows { get; set; }
}
Just in case anyone is still having issues. This worked out for me:
If the Json looks something like this:
"result": [
{
"firstname": "John",
"lastname": "Doe",
},
{
"firstname": "Max",
"lastname": "Mustermann",
}
]
ResultList.cs
public class ResultList {
[JsonProperty("result")]
public List<ResultObj> ResultObj { get; set }
}
ResultObj.cs
public class ResultObj {
[JsonProperty("firstname")]
public string FirstName { get; set; }
[JsonProperty("lastname")]
public string LastName{ get; set; }
}
And finally:
using Newtonsoft.Json;
var resultList = JsonConvert.DeserializeObject<ResultList>(jsonString);

Deserializing nested JSON arrays using RestSharp

I'm trying to deserialize the following JSON response using RestSharp. I have tried various model structures to extract the data to no avail. I keep getting tripped up on the nested arrays.
I do not have control over the service, so I can't change the format.
JSON Format:
[
{
"results": 19,
"statuscode": 200,
},
[
{
"id": 24,
"name": "bob"
},
{
"id": 82,
"name": "alice"
}
]
]
Using this model, I've been able to pull the data from the first object, but that's all. I'm not sure how exactly to read through the array that comes after the object.
public class Info
{
public int results { get; set; }
public int statuscode { get; set; }
}
Example deseralization:
var deserializer = new JsonDeserializer();
var wat = deserializer.Deserialize<List<List<Info>>>(response);
Am I just completely missing something here or are my only options to write a custom deserializer and/or use something like JSON.NET?
The problem is that your JSON array is exceptionally polymorphic: its first element is an object, and its second element is an array of objects. A more natural way to represent this would have been as a JSON object with two named properties -- but that's not what you have been given. Deserializing this directly to a c# POCO with two named properties in a single step with any serializer is going to be tricky since the JSON data model is quite different than your desired data model. Instead, it may be easiest to deserialize to an intermediate representation and convert. Luckily RestSharp has appropriate intermediate classes JsonObject and JsonArray.
Thus, if you want to deserialize to the following classes:
public class Info
{
public int results { get; set; }
public int statuscode { get; set; }
}
public class IdAndName
{
public int id { get; set; }
public string name { get; set; }
}
public class ResponseContent
{
public Info Info { get; set; }
public List<IdAndName> Data { get; set; }
}
You can do:
var array = (JsonArray)SimpleJson.DeserializeObject(response.Content);
var responseContent = (array == null ? (ResponseContent)null : new ResponseContent()
{
Info = array.OfType<JsonObject>().Select(o => SimpleJson.DeserializeObject<Info>(o.ToString())).FirstOrDefault(),
Data = array.OfType<JsonArray>().SelectMany(a => SimpleJson.DeserializeObject<List<IdAndName>>(a.ToString())).ToList()
});

Categories