How to deserialize json with a blank field? - c#

I have a json string like this:
[{
"_id": "abcd",
"name": "bender rodriguez",
"meta": {
"location": {}
},
dob": ,
}
]
The section after dob blows up:
return new JavaScriptSerializer().Deserialize<T>(json);
The problem is the empty dob. I cannot seem to find any method to handle something like this. Doesn't even seem to be a common problem? I'm not too familiar with deserializing json, what methods can I use to deal with this other than string.replace(": ,"," : null,")?

The JSON deserialiser you're using is fine, the JSON you're trying to deserialice is wrong, it's missing a value, and the initial double quotes for the dob property.
Use JSONLint to validate JSON.
If that JSON is coming from a component you control, then use a JSON serializer to serialize it properly, if not, you can fix that particular problem using this:
string myJson = "[{ \"_id\": \"abcd\", \"name\": \"bender rodriguez\", \"meta\": { \"location\": {} }, dob\": , } ]";
JavaScriptSerializer().Deserialize(myJson.Replace("dob\": ", "\"dob\": \"\""));
But if the data changes and it keeps having an invalid JSON format, there's little you can do about it but asking whoever did that component to send you valid JSON data.

Related

Deserializing Json with unexpected characters in property

My application processes a Json that contains a list of objects. The properties of these objects are not completely known to me.
Example, in the following Json, only property "Id" is known to my application:
{"msgs": [
{
"Id": "Id1",
"A": "AAA"
},
{
"Id": "Id2",
"B": "BBB"
},
{
"Id": "Id3",
"C": "CCC"
}
]}
I want to parse these messages and extract the Id of each message. This has been working fine with the following code:
public class RootElem
{
[BsonElement("msgs")]
public List<JToken> Records { get; set; }
}
then read
var rootElem = JsonConvert.DeserializeObject<RootElem>(JSON_DATA);
Once I have my rootElem, I can iterate over each record in "Records" and extract the Id.
The problem is that sometime, some of the records will contain unexpected characters.
Example:
{
"Id": "Id2",
"B": "THIS CONTAINS UNEXPECTED DOUBLE QUOTE " WHAT SHOULD I DO?"
}
I tried adding error handling settings, but that didn't work:
var rootElem = JsonConvert.DeserializeObject<RootElem>(data, new JsonSerializerSettings
{
Error = HandleDeserializationError
});
private static void HandleDeserializationError(object sender, ErrorEventArgs errorArgs)
{
var currentError = errorArgs.ErrorContext.Error.Message;
Console.WriteLine(currentError);
errorArgs.ErrorContext.Handled = true;
}
I want to be able to access the rest of the records in the list, even if one/some of them contain these invalid chars. So I'm ok if "B" value of the 2nd record is return as null, or if the 2nd record is null altogether.
How can I achieve this?
p.s. I'm using Newtonsoft Json but I'm open to using other libraries.
The issue here is that what your application is receiving is not valid JSON, hence the errors you are seeing. The input should be properly escaped prior to being submitted to this method. If this is behind an HTTP API, the appropriate response would be a 400 as the request is not in a valid format. If you really need to work around this it's possible you could implement your own JsonConverter class and decorate the converting class with it, but this may not be possible as the JSON itself is invalid and the JsonReader is going to choke when it hits it.

How do I parse the below dynamic JSON

I have a json which is badly formatted. I want to take out the status and order id from that json. Tried JSON parsing with object, but did not get the result. Please help,
My Json,
{
"formname": [
"Sale_Order_API",
{
"operation": [
"add",
{
"values": {
"Order_ID": "1250",
"Email": "xyz#yws.in",
"Order_Value": "100",
"Restaurant_Name": "HiTech",
"Order_Date": "13-Aug-2019",
},
"status": "Failure, Duplicate values found for
'Order ID'"
}
]
}
]
}
Please help.
This is my first question , please ignore mistakes.
I have tried something like this, But not able to get the inner values
dynamic resultdata = json_serializer.DeserializeObject(postData);
If I understand you correctly, you want to deserialize this JSON. On 'http://json2csharp.com/#' you can generate a C # class from your JSON. Or right by your own. There are plenty of tutorials on the Internet. In case your class, where you give the values of the Json, is called 'JSONResult', you could access the values as follows
var resultdata = JsonConvert.DeserializeObject<JSONResult>(postData);
JSONResult outPut = resultdata;
Console.WriteLine(outPut.formname[0]);
But the longer I look at the format of your JSON, the more confused I get. Where did you get the JSON from? From an API?

NewtonSoft JSON Deserialize results in still serialized data

I receive a GET request response from a REST API, in a string. As received, it looks like this:
[
{\"passport_expiration\": \"2019-09-14\", \"first_name\": \"asdfasdf\", \"last_name\": \"asdfasdf\", \"cass_status\": \"APPROVED\", \"notes\": null, \"kcm_status\": \"DENIED\", \"employment_type\": \"flight_deck\", \"employee_id\": \"10556\", \"passport_id\": \"12341234\"},
{\"passport_expiration\": \"2026-01-04\", \"first_name\": \"asdfasdf\", \"last_name\": \"asdfasdf\", \"cass_status\": \"APPROVED\", \"notes\": null, \"kcm_status\": \"DENIED\", \"employment_type\": \"flight_deck\", \"employee_id\": \"10557\", \"passport_id\": \"12341234\"},
{\"passport_expiration\": \"2026-08-31\", \"first_name\": \"asdfasdf\", \"last_name\": \"MC asdfasdf\", \"cass_status\": \"APPROVED\", \"notes\": null, \"kcm_status\": \"DENIED\", \"employment_type\": \"flight_deck\", \"employee_id\": \"10598\", \"passport_id\": \"12341234\"}
]
When I deserialize this into a dynamic:
dynamic dsCrew = JsonConvert.DeserializeObject(responseText);
dsCrew contains this:
{[
{
"passport_expiration": "2026-08-31",
"first_name": "asdfasdf",
"last_name": "MC asdfasdf",
"cass_status": "APPROVED",
"notes": null,
"kcm_status": "DENIED",
"employment_type": "flight_deck",
"employee_id": "10598",
"passport_id": "12341234"
},
{
"passport_expiration": "2026-11-16",
"first_name": "asdfasdf",
"last_name": "BLasdf",
"cass_status": "APPROVED",
"notes": null,
"kcm_status": "DENIED",
"employment_type": "flight_deck",
"employee_id": "14798",
"passport_id": "12341234"
},
{
"passport_expiration": "2025-05-05",
"first_name": "sadfasdf",
"last_name": "asdf",
"cass_status": "APPROVED",
"notes": "",
"kcm_status": "DENIED",
"employment_type": "flight_deck",
"employee_id": "14838",
"passport_id": "12341234"
}
]}
It seems to have simply removed the escape characters, converted some nulls to Empty Strings, and wrapped the whole thing in an additional set of curly braces. It's like it deserialised into just a different serialized format.
In other SO questions, answers have suggested creating a class to deserialise into:
Deserialised_Crew dsCrew = JsonConvert.DeserializeObject<Deserialised_Crew>(responseText);
But when I do that I get an exception:
"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'CASS_KCM_Update.Deserialised_Crew' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.
JsonConvert.DeserializeObject() doesn't seem to think the responseText is valid JSON. JSONLint.com says the JSON is valid.
I need a way to reference specific pieces of data:
dsCrew[0].last_name seems to reference the entire text inside the square brackets. And I can't find any way to reference with any more specificity than that. dsCrew[0][1].last_name won't work. dsCrew[0](1).last_name is right out.
I need a way to reference the names and employee_id's in this response. I'm relatively new to JSON.
The first issue is probably just what you see in the debugger. That code should be fine.
Your second problem just involves deserializing to an array, since the JSON object is an array of crew:
Deserialised_Crew[] dsCrew = JsonConvert.DeserializeObject<Deserialised_Crew[]>(responseText);
From there on, your code dsCrew[0].last_name should work as expected.

Deserialize Nested JSON with C# Without Class Declaration

I am trying to deserialize an object dynamically but unsure what the syntax is:
The JSON looks like this:
"Id": 2750,
"Rev": 1,
"Fields": {
"System.AreaPath": "test",
"System.TeamProject": "proj",
"System.IterationPath": "Ipath",
"System.WorkItemType": "type"
}
I know they can be accessed like this:
var resultString = response.Content.ReadAsStringAsync().Result;
var jsonObject = JObject.Parse(resultString);
string ID= jsonObject["id"].ToString();
But I am not sure how to get to the values nested in Fields directly.
I know I can iterate through jsonObject["Fields"] but I want to access them via something like jsonObject["Fields\\System.AreaPath"].ToString(); or whichever is the correct syntax, if it exists that is.

Json.Net Serialize Complex Object to Xml Attribute And Value

Let's say I have a Json object that looks like this:
{
"Phones": [
{
"Phone": {
"Value": 123,
"#Type": "Foo"
}
}
]
}
I want to call JsonConvert.DeserializeXmlNode() but would like the resulting XML to look like this:
<Phones>
<Phone Type="Foo">123</Phone>
</Phones>
Currently Value is being deserialized to an xml element as a child of Phone, but I want it to be the XML value of Phone. Is there a way to do this using Json.Net, like a special operator that tells it to deserialize it as such, without having to create a custom serializer? Any help is apppreciated.
I just figured it out. using
"Phone": {
"#Type": "Foo",
"#text": 123
}
gives me the expected result. #text tells it not to create a child element for that value.

Categories