Deserializing Json Value to C# List<String> - c#

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"]
}

Related

How can I deserialize this specific json string?

I am trying to deserialize the following json string using Newtonsoft Json. I am able to get the string successfully, but when I try using JsonConvert.DeserializeObject<ServerList>(response, settings);, the try catch fails.
[
{"endpoint":"127.0.0.1","id":6,"identifiers":["steam:","license:","xbl:","live:","discord:"],"name":"Blurr","ping":160},
{"endpoint":"127.0.0.1","id":7,"identifiers":["steam:","license:","xbl:","live:","discord:"],"name":"Knight","ping":120}
]
I believe my issue is because the players array being unnamed.
I have tried [JsonProperty("")] and [JsonProperty] for the Users var, I have also tried using List and Array instead of IList.
Here is the object. This may be completely wrong, I have tried many ways of doing this.
public class ServerList
{
// I have tried many ways of doing this array/list. This is just the latest way I tried.
[JsonProperty]
public static IList<Player> Users { get; set; }
}
public class Player
{
[JsonProperty("endpoint")]
public static string Endpoint { get; set; }
[JsonProperty("id")]
public static string ServerId { get; set; }
[JsonProperty("identifiers")]
public static IList<string> Identifiers { get; set; }
[JsonProperty("name")]
public static string Name { get; set; }
[JsonProperty("ping")]
public static int Ping { get; set; }
}
I am expecting to get a 'ServerList' object returned with a list of all the players connected to the server.
Ask any questions you need to, I don't often work with json in this format. Thank you in advance!
ERROR: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
Simplest way: Your json is an array, so deserialize to an array:
JsonConvert.DeserializeObject<Player[]>(response,settings);
As noted in the comments, properties on the Player should not be static.
If you insist on an object structure similar to what you posted, an object with a Usersproperty, even though it's not present in the JSON, that is also possible, by implementing a custom JSON converter. There's an article with an example of that here: https://www.jerriepelser.com/blog/custom-converters-in-json-net-case-study-1/
HOWEVER; I would recommend sticking to the types present in the json, and perhaps later construct the object that makes sense to the model in your program. This way, what you deserialize are true to the json you are getting, but make no sacrifices on the model you'd like:
var players = JsonConvert.DeserializeObject<Player[]>(response,settings);
var serverList = new ServerList {Users = players};

Using Newtonsoft JsonConvert to serialize and deserialize simple class

I'm trying to simply serialize and deserialize a simple class with JsonConvert.SerializeObject(obj) and JsonConvert.DeserializeObject(string).
I'm using this in a custom TypeConverter for a QueryParameter in .NET Web API Core 2.1.
But I'm getting very strange behavior. My class looks like this:
public class ListRequestDto {
public bool? WithCreator { get; set; }
public int? Skip { get; set; }
public int? Limit { get; set; }
}
And I'm trying to do the following:
var test = new ListRequestDto {
WithCreator = true,
Skip = 0,
Limit = 15
};
string ttt = JsonConvert.SerializeObject(test);
But I'm getting the following output:
"MyNameSpace.ListRequestDto"
If I try it the other way around:
string json = "{ WithCreator: true, Skip: 0, Limit: 15 }";
JsonConvert.DeserializeObject<ListRequestDto>(json);
I get the following exception:
Newtonsoft.Json.JsonSerializationException: "Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'MyNameSpace.ListRequestDto' because the type requires a JSON string value to deserialize correctly.
To fix this error either change the JSON to a JSON string value 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 'Skip', line 1, position 8."
I tried to remove the nullable fields (replacing them with regular primitives) but that resulted int he exact same error.
The strange thing is, that if I provide the same class as a body it works. And as far as I know Web API Core also uses the Newtonsoft Json Parser.
I do not know why it is necessary, but when I put [JsonObject] on my class it suddenly works.
The exception actually told me to do that, but I do not understand why it is necessary when in no documentation this is used in such a case.
So bascially doing the following solved the problem:
[JsonObject]
public class ListRequestDto {
public bool? WithCreator { get; set; }
public int? Skip { get; set; }
public int? Limit { get; set; }
}

How to convert a Json string to a class that has a list in Json.Net with C# when the json has an array one level deeper

I have a C# Application in which I am using Json.Net from Nuget.
I get a json from my server which I need to convert into a C# object and with a few modifications I will send it back to the server as json.
Here's my model in C# (which I got after converting the server xsd)
public class Tags
{
public List<Tag> tagData { get; set; }
}
public class Tag
{
public string name {get; set;}
}
Here's my JSON string that is obtained from the server and an attempt at conversion to my model
//Json string obtained from server (hardcoded here for simplicity)
string json = "{tagData: {tags : [ { name : \"John\"}, { name : \"Sherlock\"}]}}";
//An attempt at conversion
var output = JsonConvert.DeserializeObject<Tags>(json);
This is the exception I get with the above code
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[jsonnetExample.Tag]' 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<T>) 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 'tagData.tags', line 1, position 17.
After understanding the above message I tried the following 2 things in the hope of fixing it.
A.I tried putting a JsonProperty to my first model.
[JsonProperty(PropertyName = "tags")]
This didn't throw the exception anymore but the output tagData was null.
B. I modified my model as follows
public class Tags
{
public WrapTag tagData { get; set; }
}
public class WrapTag
{
public List<Tag> tags { get; set; }
}
public class Tag
{
public string name {get; set;}
}
This didn't throw any exception and populated the objects as expected. But Now I lost the one to one mapping between xsd(classes from the server) to my client model classes. Is it possible to get this deserialization working without the creation of the WrapTag class?
I would be very glad if someone can point me in the right direction.
Thanks in advance.
Here's one option, using JObject.Parse:
string json = "{tagData: {tags : [ { name : \"John\"}, { name : \"Sherlock\"}]}}";
List<Tag> tagList = JObject.Parse(json)["tagData"]["tags"].ToObject<List<Tag>>();
// or:
// List<Tag> tagList = JObject.Parse(json).SelectToken("tagData.tags")
// .ToObject<List<Tag>>();
Tags tags = new Tags { tagData = tagList };

Deserialization of not so well formated json

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!

how to name c# class fields to be able deserialize json field names with invalid characters

I am using JSON.NET to deserialize some JSON responses that I have.
I have been successful up to now.
In order for JSON.NET to properly deserialize the objects the field name in the class needs to be called exactly as in JSON. The problem is I have some fields that have funky characters in their name that I can't use in C# like {"(.
Does anyone know how to rename the fields so they get mapped properly?
Here is a short example of what works.
JSON input:
{
"contact_id": "",
"status": "Partial",
"is_test_data": "1",
"datesubmitted": "2013-10-25 05:17:06"
}
Deserialized class:
class DeserializedObject
{
public string contact_id;
public string status;
public int is_test_data;
public DateTime datesubmitted;
}
Deserialization:
var deserialized = JsonConvert.DeserializeObject<DeserializedObject>(jsonInput);
This gets mapped properly. The problem starts when I try to process the following field:
{
"contact_id": "",
"status": "Partial",
"is_test_data": "1",
"datesubmitted": "2013-10-25 05:17:06",
"[variable("STANDARD_GEOCOUNTRY")]": "Germany"
}
Deserialized class:
class Output
{
public string contact_id;
public string status;
public int is_test_data;
public DateTime datesubmitted;
public string variable_standard_geocountry; // <--- what should be this name for it to work?
}
I would appreciate any help.
With JSON.NET, you'd just need to put a JsonProperty attribute on the property, like:
class Output
{
public string contact_id;
public string status;
public int is_test_data;
public DateTime datesubmitted;
[JsonProperty("[variable(\"STANDARD_GEOCOUNTRY\")]")]
public string variable_standard_geocountry; // <--- what should be this name for it to work?
}
This will now deserialize. This assumes that your JSON is properly formatted with those quotation marks, like:
{
"contact_id": "",
"status": "Partial",
"is_test_data": "1",
"datesubmitted": "2013-10-25 05:17:06",
"[variable(\"STANDARD_GEOCOUNTRY\")]": "Germany"
}
You could use the JsonProperty attribute and set the name like this ...
`
class Output
{
public string contact_id;
public string status;
public int is_test_data;
public DateTime datesubmitted;
[JsonProperty("geocountry")]
public string variable_standard_geocountry; // <--- what should be this name for it to work?
}
`
Here's a link to the documentation as well which may have other info you might find helpful.
http://james.newtonking.com/json/help/?topic=html/JsonPropertyName.htm

Categories