Deserialization of not so well formated json - c#

I need help or some inspiration for some strange json deserialization.
This is the json I recieve from a service (can't change it, its an external service):
{
"status":"OK",
"statuscode":200,
"payload":{
"solarforecast":{
"5876":{
"2014-06-06 23:00:00":{
"bh":0,
"dh":0
},
"2014-06-07 00:00:00":{
"bh":0,
"dh":0
},
[...]
}
}
}
I made a call to get values for a object with id 5876.
So if I made a call for object with id 1254, the json changed this way:
[...]
"solarforecast":{
"1254":{
"2014-06-06 23:00:00":{
[...]
I now want to create an c# object from this json code with help of Newton ;) .
My frist Problem is that the property name (aka object id) is different for any object call and its a number.
My second problem are the sub objects with undefinded count. I think in a well formed json object it has to be somethink like this (see "[" brackets):
"solarforecast":{
"5876":[
"2014-06-06 23:00:00":{
"bh":0,
"dh":0
},
"2014-06-07 00:00:00":{
"bh":0,
"dh":0
},
[...]
]
}
Has anybody a trick or solution how to well deserialize this json into a proper c# class?
I try to get somethink like that as result:
public class Payload
{
[JsonProperty("solarforecast")]
public SolarForecast SolarForecast;
}
public class SolarForecast
{
[JsonProperty("???")]
public IEnumerable<SolarForecastTimeSet> SomeObjectID;
}
public class SolarForecastTimeSet
{
[JsonProperty("???")]
public decimal TimeStamp;
[JsonProperty("dh")]
public decimal DiffusRadiationHorizontal;
[JsonProperty("bh")]
public decimal DirectRadiationHorizontal;
}
Thanks for your help!!
Steffen

Ok figured out how it will work!
Object tree has to be:
public class Payload
{
[JsonProperty("solarforecast")]
public Dictionary<int, Dictionary<DateTime, SolarForecastTimeSet>> SolarForecast;
}
public class SolarForecastTimeSet
{
[JsonProperty("dh")]
public decimal DiffusRadiationHorizontal;
[JsonProperty("bh")]
public decimal DirectRadiationHorizontal;
}
Thanks #andyp for his dictionary hint!

Related

Deserializing Json Value to C# List<String>

I'm having an issue with converting a one part of a JSON string to C# List. The original code didn't have the [JsonProperty] and it that's where the issue started. I added the [JsonProperty] to the MdId value, but the issue is still happens.
C# Class
public class PendingPatientDocumentRecord
{
public int PatientDocumentFileMapId;
public short ContextTypeId;
public string PatientVisitId;
public List<string> BillingIds;
public DateTime? DateOfService;
[JsonProperty("MdId")]
public List<string> MdId;
}
Deserialization code
List<PendingPatientDocumentRecord> pendingDocuments = JsonConvert.DeserializeObject<List<PendingPatientDocumentRecord>>(pendingDocumentsJson);
JSON String:
[
{
"PatientDocumentFileMapId":12,
"ContextTypeId":3,
"DateOfService":"08/31/2022",
"MdId":"ala"
}
]
Error:
Error converting value "ala" to type System.Collections.Generic.List`1[System.String]'. Path '[0].MdId'
MdId needs to be an array so that it can be converted to a list. You don't need the JsonProperty attribute.
{
"PatientDocumentFileMapId": 12,
"ContextTypeId": 3,
"DateOfService": "08/31/2022",
"MdId": ["ala"]
}

Weird JSON Parsing situation with C#

I have a very strange situation with a customer's JSON. They send an array of objects named as the ID (which is a number) :
Instead of the expected object name allowing for a simple parsing, such as "amenity".
How can we parse this into a List of objects containing ID and Name? Here's the exact JSON text:
"amenities":{
"2194":{
"id":"2194",
"name":"Breakfast for 2"
},
"2192":{
"id":"2192",
"name":"Free WiFi"
}
}
And there are other case when we have more fields , not only id, and name inside each object
"amenities":{
"2194":{
"id":"2194",
"name":"Breakfast for 2",
"validto" : "2022-10-30"
},
"2192":{
"id":"2192",
"name":"Free WiFi",
"validto" : "2022-10-30"
}
}
Thank you all!!!
You need two classes, one to be the main(Class1) where the json will be converted into and another class(Class2) for the object in the array. Then you can convert the dictionary in the main into a List of Class2 values of the dictionary.
public class MyClass1{
public Dictionary<string,MyClass2> amenities;
}
public class MyClass2{
public string id;
public string name;
public string validto;
}
First deserialize into MyClass1, then get the Values from the Dictionary and turn into List.
List<MyClass2> list = JsonConvert.DeserializeObject<MyClass1>(jsonstring).amenities.Values.ToList()

Parse Json object of unpredictable type name

I'm trying to parse a JSON answer from a RESTfull Api. I'm usally using NewtonSoft Json.Net to deserialize objects (whith the help of tools like Json2Csharp).
This time though, the answer I get from the webservice is more complex.
The answer is like as follow : (see full answer here)
[
{
"semester": 0,
"modules": {
"B-ANG-052": {...},
"B-ANG-056": {...},
...
},
{
"semester": 1,
"modules": {
"BSU-CPR-125": {...},
"BSU-BPR-098": {...},
...
},
...
[
Problem is, objects B-ANG-052, B-ANG-056, BSU-CPR-125 and BSU-BPR-098 are same type, but their number and name vary, and I cannot predict their name and number ahead of query.
Idealy, I would like to be able to create something like
public class ModuleRessource
{
// B-ANG-052 & Co stuff
}
public class Modules
{
public List<ModuleRessource> Modules { get; set; }
}
public class RootObject
{
public int semester { get; set; }
public Modules Modules { get; set; }
}
But obviously Json.Net throws an Exeption when I try to do that.
I would very appreciate some help on the matter, because I haven't been able to find any clue.
Thanks in advance !
public class Modules
{
public List<ModuleRessource> Modules { get; set; }
}
Change this to:
public class Modules {
public Dictionary<string, someObject> { get; set; }
}
someObject should be whatever is in {...} with the key B-ANG-052. This only works if the keys are unique, of course. Then you can grab the dictionary's keys and use them to loop through and grab the someObject. I don't really know how you're going to be able to create an object and use that object without ever knowing what the object is called. If the {...} is always the same, create a class and deserialize it to a someObject in the dictionary.
You could also try to use a dynamic type, but you'll still run into the problem of not knowing what the object is called. You'd to use reflection to loop through the properties of your main object then to retrieve them.

Using JSON.NET to deserialize to a derived class

I have been battling with this for few hours and I can't figure out a solution.
Using JSON.NET, I'm trying to deserialize some data to one or another derived class, BUT I want to target the right derived class based on a field that actually is in those data...
Here is a simplified example :
public class BaseFile {
public string Name{get;set;}
}
public class Directory : BaseFile {
public int FileSize {get;set;}
}
public class Video : BaseFile {
public int Duration{get;set}
}
I receive those JSON formatted data :
{
"files": [
{
"content_type": "application/x-directory",
"size": 566686478
},
{
"content_type": "video/x-matroska",
"duration": 50
}
}
Now, I want to use JSON.NET, based on the content_type field, to instantiate either a Directory object (if the content_type is application/x-directory) or a Video object (if the content_type is video/x-matroska).
The simple solution is to deserialize all the content to the base class, and then transform those into their respective derived classes, but I don't find this effective so I'm wondering if there's another solution out there !
Thank you in advance for your input(s).
A friend of mine pointed me this post that solves my problem :
Deserializing heterogenous JSON array into covariant List<> using JSON.NET
I just tried it and for my case, the adapted code is written like this :
private BaseFile Create(Type objectType, JObject jObject)
{
var type = (string)jObject.Property("content_type");
switch (type)
{
case "application/x-directory":
return new Directory();
case "video/x-matroska":
return new Video();
default:
return new BaseFile();
}
}

Deserializing Json with numbered keys in ServiceStack

I have such Json:
{
data:{
"50":{"id":"50","name":"test", etc...},
"51":{"id":"51","name":"test", etc...},
"53":{"id":"53","name":"test", etc...},
...
}
}
What is the correct way to deserialize this Json?
[UPDATED]
I think I must to adjust my question. Is it possible to parse Json using class with description of objects. E.g. I have such class and Json which I parse with .FromJson():
public class Data
{
public ...
}
public class Category
{
public int Id{get;set;}
public string Name{get;set;}
}
What should be instead three dots?
Your json contains an object O. This object has a member data that is a dictionary from strings or ints to your category objects. So try something like:
class Root
{
public Dictionary<int, Category> data;
}
var o = JavaScriptSerializer.Deserialize<Root>(json);
If you are using servicestack.text just do
var v = myJson.FromJson();
Don't forget that servicestack is best used when serialization also made with servicestack.
the best way to deserialize Json object to c# class in JSON.NET project (found on codeplex)
the deserialize example is:
JsonConvert.DeserializeObject<Category>(jsonString);

Categories