{
"578080": {
"success": true,
"data": {
"type": "game",
"name": "PLAYERUNKNOWN'S BATTLEGROUNDS",
"steam_appid": 578080,
"required_age": 0,
"is_free": false,
}
}
}
This is from the Steam API. As you can see the root key the ID itself, so I don't know how to deserialize this to an object. I've seen other questions regarding unknown property names, but can't seem to apply those solutions for when the root name is unknown.
One way to do this is to Deserialize to Dictionary
Classes
public class Data
{
public string type { get; set; }
public string name { get; set; }
public int steam_appid { get; set; }
public int required_age { get; set; }
public bool is_free { get; set; }
}
public class SomeClass
{
public bool success { get; set; }
public Data data { get; set; }
}
Usage
var result = JsonConvert.DeserializeObject<Dictionary<string, SomeClass>>(json);
If you don't care about making POCO models for your deserialized data and just want to grab some of the properties using a dynamic, you can use JsonExtensionData to get a JToken of the relevant subobject:
public class Foo
{
[JsonExtensionData]
public Dictionary<string, JToken> ExtensionData {get; set;}
}
dynamic obj = JsonConvert.DeserializeObject<Foo>(json).ExtensionData.Single().Value;
Console.WriteLine(obj.success);
Console.WriteLine(obj.data.name);
This approach would be particularly useful if you could reuse Foo across several different types of responses since it doesn't care at all about the object schema.
You can use an anonymous type deserialization to parse JSON data like this, without creating classes. I assumed there is only one Id("578080") present in your data.If more Id's present, you can create an array for those Id's. Hope It Works.
var finalResult=JsonConvert.DeserializeAnonymousType(
yourdata, // input
new
{
Id=
{
new
{
success="", data=""
}
}
}
);
console.write(finalResult.Id);// getting Id 578080
console.write(finalResult.Id.success);
console.write(finalResult.Id.data.type);
Related
I already looked at a lot of other questions with the same problem but never found a definitive solution that actually works for me. I tried using the JsonExtensionData Attribute, that doesn't work though since I can't convert my other data class to an object and it throws the Invalid extension data attribute on 'NAMESPACE'. Member 'Sols' type must implement IDictionary<string, JToken>. error.
My current data model class looks like this
public partial class Mars
{
public Dictionary<string, Sol> Sols { get; set; }
[JsonProperty("sol_keys")]
public List<long> SolKeys { get; set; }
}
public partial class Sol
{
[JsonProperty("AT")]
public At At { get; set; }
[JsonProperty("First_UTC")]
public DateTimeOffset FirstUtc { get; set; }
[JsonProperty("Last_UTC")]
public DateTimeOffset LastUtc { get; set; }
[JsonProperty("Season")]
public string Season { get; set; }
}
public partial class At
{
[JsonProperty("av")]
public double Av { get; set; }
[JsonProperty("ct")]
public long Ct { get; set; }
[JsonProperty("mn")]
public double Mn { get; set; }
[JsonProperty("mx")]
public double Mx { get; set; }
}
The json data looks like this
{
"651":
{
"AT":
{
"av": -61.957,
"ct": 302204,
"mn": -96.733,
"mx": -15.877
},
"First_UTC": "2020-09-25T02:42:14Z",
"Last_UTC": "2020-09-26T03:21:49Z",
"Season": "summer"
},
"652": {
"AT": {
"av": -65.002,
"ct": 278608,
"mn": -96.111,
"mx": -15.653
},
"First_UTC": "2020-09-26T03:21:50Z",
"Last_UTC": "2020-09-27T04:01:24Z",
"Season": "summer"
},
"sol_keys": [
"646",
"647",
"648",
"649",
"650",
"651",
"652"
]
}
I can't really modify the json data since I get it from an api.
I basically just want to select one of the numbers and then get the Sol data of that object.
Any help would be appreciated.
The JSON doesn't fit well with the C# type system. However, you can still use Json.Net to parse it. You just need to introduce some extra steps.
First step is to parse the JSON to a JObject:
var jObject = JsonConvert.DeserializeObject<JObject>(json);
Then you can extract the sol_keys:
var solKeys = jObject.GetValue("sol_keys").ToObject<long[]>();
Now it becomes a bit tricky. If you remove the sol_keys from the JSON (in this case the parsed JSON) it has the structure of a dictionary of Sol objects that you are able to parse:
jObject.Remove("sol_keys");
var mars = jObject.ToObject<Dictionary<long, Sol>>();
Now you have both solKeys and mars parsed from the JSON. Furthermore the solKeys and the keys in the dictionary share the same type (long).
I have this Json:
{
"UpdatePack":"updatePacks\/1585654836.pack",
"Updates":[
{
"Name":"MsgBoxEx",
"version":"1.5.14.88",
"ChangeLog":"BugFix: Form didn't resize correct.",
"Hash":"5FB23ED83693A6D3147A0485CD13288315F77D3D37AAC0697E70B8F8C9AA0BB8"
},
{
"Name":"Utilities",
"version":"2.5.1.58",
"ChangeLog":"StringManagement updated.",
"Hash":"05E6B3F521225C604662916F50A701E9783E13776DE4FCA27BE4B69705491AC5"
}
]
}
I have created 2 classes to be used to Deserialize it.
class UpdatesList
{
public string Name { get; set; }
public string Version { get; set; }
public string ChangeLog { get; set; }
public string Hash { get; set; }
}
class JsonObjectHolder
{
public string UpdatePack { get; set; }
//public Dictionary<int, MyData> { get; set; }
public Dictionary<int, UpdatesList> Updates { get; set; }
}
But when I try to access the dictionary, I keep getting Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at " Console.WriteLine(jsonTest.Dict.Count);"
Am I Deserializing it wrong, or do I need to do some thing else to access the result of the dictionary?
I'm new to both C# and Json.
I hope that some one could point me in the right direction on how to handle this.
I'm using Visual Studio 2019 latest update, and .net 4.8.
Regards
/LR
You code doesn't work because 0 and 1 tokens just a properties, not the array items (you don't have square brackets [] around them). You can parse these values to desired structure manually using JObject
var json = JObject.Parse(your_json_string);
var dict = new Dictionary<int, UpdatesList>();
foreach (var item in json.Properties())
{
if (item.Value.Type == JTokenType.Object)
{
var index = int.Parse(item.Name);
var updateList = item.Value.ToObject<UpdatesList>();
dict.Add(index, updateList);
}
}
var holder = new JsonObjectHolder
{
UpdatePack = json["Updates"]?.Value<string>(),
Dict = dict
};
Update: According to OP changes made to JSON it might be deserialized even more simply
var list = json["Updates"]?.ToObject<List<UpdatesList>>();
var holder = new JsonObjectHolder
{
UpdatePack = json["UpdatePack"]?.Value<string>(),
Dict = list.Select((updatesList, index) => new { updatesList, index })
.ToDictionary(x => x.index, x => x.updatesList)
};
The main point here is that Updates is an array of items, not the key-value collection. It can be transformed into Dictionary<int, UpdatesList> using ToDictionary method from System.Linq (or just use List<UpdatesList> as is)
The exception you're getting essentially means the value is being accessed before the object is initialized.
A better, simpler and cleaner way to doing it is using NewtonSoft. (you can easily get it as a Nuget package)
example:
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
and then usage:
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
Source: https://www.newtonsoft.com/json/help/html/DeserializeObject.htm
I don't see why you need Dictionary<int, UpdatesList> Updates, when you can easily just use List<Update> Updates, since your updates are in a JSON array.
I would model your classes like this:
public class Update
{
public string Name { get; set; }
public string Version { get; set; }
public string ChangeLog { get; set; }
public string Hash { get; set; }
}
public class RootObject
{
public string UpdatePack { get; set; }
public List<Update> Updates { get; set; }
}
You can then deserialize with:
JsonConvert.DeserializeObject<RootObject>(json);
Try it out on dotnetfiddle.net
Note: To convert JSON to C# classes, you can go to Edit -> Paste Special -> Paste JSON as Classes inside Visual Studio. Make sure you have copied the JSON to your clipboard before using it. You will get classes similar to above.
your data and the class is not compatible. if you change the string like this it would work.
change "Updates" to "UpdatePack" and add "Dict" around the dictionary items.
{
"UpdatePack":"updates\/4D1D7964D5B88E5867324F575B77D2FA.zip",
"Dict":{
"0":{
"Name":"MsgBoxEx",
"Version":"1.0.123.58",
"ChangeLog":"Bugfix:Form didn't resize correct",
"hash":"AA94556C0D2C8C73DD217974D252AF3311A5BF52819B06D179D17672F21049A6"
},
"1":{
"Name":"Utilities",
"Version":"1.5.321.87",
"ChangeLog":"StringManagement updated",
"hash":"2F561B02A49376E3679ACD5975E3790ABDFF09ECBADFA1E1858C7BA26E3FFCEF"
}
}
}
I am trying to deserialize an HTTPWebRequest response (Json) to a c# object/class, but am having trouble. A collection with 10 instances of the object are returned, and all the objects are null.
Here is the json:
[
{
"id":2227,
"user_id":441,
"grades":
{"html_url":"https://...",
"current_score":91.26,
"current_grade":null,
},
"sis_account_id":"11",
"user":
{"id":441,
"name":"Nicholas Bailey",
}
},
Here are the classes:
public class Grade
{
public string html_url { get; set; }
public decimal current_score { get; set; }
public string current_grade { get; set; }
}
public class User
{
public int id { get; set; }
public string name { get; set; }
}
public class Enrollment
{
public int id { get; set; }
public int user_id { get; set; }
public Grade grades { get; set; }
public string sis_account_id { get; set; }
public User user { get; set; }
}
public class RootObject
{
public Enrollment enrollment { get; set; }
}
And here is my code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://(some uri)");
WebResponse response = request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string content = sr.ReadToEnd();
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
var outObject = JsonConvert.DeserializeObject<List<RootObject>>(content, settings);
I have been looking at a lot of code on google but have not found a situation that is close to mine. Also, I'm a bit green on generic collections. The code runs fine but in the debugger the "outObject" contains 10 entries, each with an "Enrollment" object that is null.
I also have tried this with json that has well over 10 entries, but it still comes up with 10. But I'm more focused on the nulls at this point (One thing at a time!). For the sake of brevity I have removed several entries in the json, but the main pattern (an enrollment object with a grades object and a user object embedded in it) remains.
Any help would be much appreciated. Thanks.
Deserialize to List<Enrollment> not List<RootObject>:
var enrollment = JsonConvert.DeserializeObject<List<Enrollment>>(content, settings);
The first JSON object in the root array has properties "id", "user_id" and so on that correspond to the members of Enrollment. Conversely there is no property "enrollment" in the JSON anywhere.
Sample fiddle.
Update
You asked, I tried this and now I'm getting an exception "Error converting value {null} to type 'System.Int32'. Path '[0].associated_user_id', line 1, position 165." associated_user_id was removed for brevity but I will add it back into my code. Any ideas?
Somewhere your data model you must have the following member (field or property):
public int associated_user_id;
Change this to a nullable:
public int? associated_user_id;
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.
Assuming I have a JSON file with the following structure. How I can access the names of the properties in the metadata field.
{
"mappings": {
"basedoc_12kja": {
"properties": {
"created": {
"type": "date",
"format": "dateOptionalTime"
},
"customerID": {
"type": "string"
},
"deleted": {
"type": "boolean"
},
"documentID": {
"type": "string"
},
"id": {
"type": "string"
},
"metadata": {
"properties": {
"Cert": {
"type": "string"
},
"Exp_date": {
"format": "dateOptionalTime"
},
}
}
}
}
}
}
Mappings is an array of documents, each subfield of mappings has a different code. I want to obtain the metadata fields of each document to find out which metadata fields are common between them.
I haven't been able to instantiate this documents.
var response = esReader.GetIndicesMapping();
foreach (var mapping in response.Response.Values)
{
// Parse JSON into dynamic object, convenient!
dynamic results = JObject.Parse(mapping);
List<DocumentType> deserializedObject = JsonConvert.DeserializeObject<List<DocumentType>>(mapping);
}
Exception
{"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[DocumentType]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo 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.\r\nPath 'mappings', line 2, position 14."}
The desire result is to obtain the name of Cert and Exp_date fields
EDIT
public class DocumentType
{
public string Id { set { DocumentID = value; } get { return DocumentID; } }
public string DocumentID { set; get; }
public DateTime Created { set; get; }
.
.
.
public Dictionary<string, object> Metadata { set; get; }
}
The problem here is that your data structure does not match the JSON:
There are no arrays in the JSON. So there is no way you will be able to deserialize that into a C# List.
The "DocumentType" class doesn't match the JSON at all. The class has properties Created, CustomerID, and Deleted which are things like DateTime and string. But the JSON doesn't have those as DateTime or string. They are objects with subproperties named "type" and "format." The property "Metadata" isn't a dictionary: it is an object with a single property named "properties" which should probably be a dictionary.
The case doesn't match.
Don't do that weird thing with Id and DocumentId. The class should match the JSON exactly and literally. No business logic hidden in properties.
The root object has a property called "mappings" so you will need to drill-down before you get to the documents.
Once you successfully get the document, you will need to drill down to the property named "properties" to get to the fields you are interested in.
I suspect there could be multiple documents, and that the "mappings" property contains a list of those documents, where the property names are dynamic and correspond to the name of the document. It is entirely plausible to handle that but not using a deserialization + List approach.
I see 3 approaches here:
Fix the JSON. Not sure if this is possible in your case. If so, start by making mappings hold an array instead of having each document be a property named by the document name.
Fix the deserialization code to match the JSON document. json2csharp did an excellent job so start with that. It just doesn't know that "mappings" is really a Dictionary, not just a thing with a property named "basedoc12_kja."
Don't deserialize it at all. Just query for the metadata. take a look at http://www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm which shows several ways to query JSON using JObject properties and LINQ.
Option 1
Example of a slightly cleaned-up JSON if you go that route:
{
"mappings": [
{
"name"" : "basedoc_12kja",
"properties": {
""created": "20150522",
etc.
},
Notice "mappings" is an array and the name became a property of the document. Now you can make a List<> or use JArray. Even better is to get rid of the unused stuff at the top, like this:
[
{
"name" : "basedoc_12kja",
"properties": {
"created"": "20150522",
etc.
},
]
Now it is just an array with no "mappings" at all.
** Option 2 **
Here is code that will do this via deserialization. There are two parts. Step one is to use what json2charp produced. I'll include that here for reference:
public class Created
{
public string type { get; set; }
public string format { get; set; }
}
public class CustomerID
{
public string type { get; set; }
}
public class Deleted
{
public string type { get; set; }
}
public class DocumentID
{
public string type { get; set; }
}
public class Id
{
public string type { get; set; }
}
public class Cert
{
public string type { get; set; }
}
public class ExpDate
{
public string format { get; set; }
}
public class Properties2
{
public Cert Cert { get; set; }
public ExpDate Exp_date { get; set; }
}
public class Metadata
{
public Properties2 properties { get; set; }
}
public class Properties
{
public Created created { get; set; }
public CustomerID customerID { get; set; }
public Deleted deleted { get; set; }
public DocumentID documentID { get; set; }
public Id id { get; set; }
public Metadata metadata { get; set; }
}
public class Basedoc12kja
{
public Properties properties { get; set; }
}
public class Mappings
{
public Basedoc12kja basedoc_12kja { get; set; }
}
public class RootObject
{
public Mappings mappings { get; set; }
}
Then, rename Basedoc12kja to DocumentType, and change RootObject to hold a dictionary. You get this:
public class DocumentType
{
public Properties properties { get; set; }
}
public class RootObject
{
public Dictionary<string, DocumentType> mappings { get; set; }
}
And if you want to get to properties other than just Cert and Exp_date then change Metadata to this:
public class Metadata
{
public Dictionary<string,object> properties { get; set; }
}
Now that can deserialize your document:
JObject results = JObject.Parse(mapping);
RootObject ro = results.ToObject<RootObject>()
You can enumerate through the mappings and get to the properties. They are still messy because of the JSON structure, but you can at least get there.
I hope this helps!
What you have here is a hierarchical dictionary of named properties, where each property can have a type, a format, and possibly a nested dictionary of named child properties -- metadata in your case. You can represent this with the following data model:
[DataContract]
public class PropertyData
{
[DataMember(Name="type", EmitDefaultValue=false)]
public string Type { get; set; }
[DataMember(Name = "format", EmitDefaultValue = false)]
public string Format { get; set; }
[DataMember(Name = "properties", EmitDefaultValue = false)]
public Dictionary<string, PropertyData> Properties { get; set; }
}
[DataContract]
public class Mappings
{
[DataMember(Name = "mappings", EmitDefaultValue = false)]
public Dictionary<string, PropertyData> DocumentMappings { get; set; }
}
(This data model doesn't capture the fact that a given property (probably) can only be a simple type or a complex type with nested properties - but not both. It would seem to suffice for your needs however.)
Then, given the JSON above, you would read it in and convert it to a dictionary of document name to metadata property name as follows:
var mappings = JsonConvert.DeserializeObject<Mappings>(json);
Debug.WriteLine(JsonConvert.SerializeObject(mappings, Formatting.Indented)); // Verify that all was read in.
var metadataNames = mappings.DocumentMappings.ToDictionary(doc => doc.Key, doc => doc.Value.Properties["metadata"].Properties.Select(p => p.Key).ToList());
Debug.WriteLine(JsonConvert.SerializeObject(metadataNames, Formatting.Indented)); // Inspect the resulting mapping table.
And the result is the dictionary of metadata names you want:
{
"basedoc_12kja": [
"Cert",
"Exp_date"
]
}
If you are concerned that the nested metadata might be missing sometimes and so generate NullReferenceExceptions in the query above, you can add null checks as follows:
// Extension methods to query or walk through nested properties, avoiding null reference exceptions when properties are missing
public static class PropertyDataExtensions
{
public static IEnumerable<KeyValuePair<string, PropertyData>> GetProperties(this PropertyData data)
{
if (data == null || data.Properties == null)
return Enumerable.Empty<KeyValuePair<string, PropertyData>>();
return data.Properties;
}
public static PropertyData GetProperty(this PropertyData data, string name)
{
if (data == null || data.Properties == null)
return null;
PropertyData child;
if (!data.Properties.TryGetValue(name, out child))
return null;
return child;
}
}
And then:
var metadataNamesSafe = mappings.DocumentMappings.ToDictionary(doc => doc.Key, doc => doc.Value.GetProperty("metadata").GetProperties().Select(p => p.Key).ToList());