How do I parse the below dynamic JSON - c#

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?

Related

Deserializing json without key name

i have json answer, like this, without key names, only values
[
[
1645724820000,
"35893.01000000",
"35898.38000000",
"35850.01000000",
"35876.07000000",
"10.19782000",
1645724879999,
"365831.59479120",
335,
"2.90744000",
"104298.60366850",
"0"
],
[
1645724880000,
"35876.79000000",
"35910.93000000",
"35864.93000000",
"35910.93000000",
"8.15710000",
1645724939999,
"292722.41648950",
326,
"3.18438000",
"114275.09871200",
"0"
]
]
i try deserializing with Newtonsoft, next C# code
public class Root
{
public List<List<String>> MyArray { get; set; }
}
//Root Pair = JsonConvert.DeserializeObject<Root>(Data2Json);
but it does't work, i'm begginer programmer, help pls, how i can deserializing it json. I guess it needs to be deserialized into some kind of array or list of values since there are no key names, but I don't know how, Google doesn't help anymore
you can try this code
List<List<string>> list = JsonConvert.DeserializeObject<List<List<string>>>(json);

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.

Extract schema from JSON data in C#

I have below JSON schema which works ok with JsonConvert.DeserializeObject. I am able to extract schema directly from it but when it comes to JSON Data string, then I am not sure how to extract schema.
{
"fields": [
{
"name": "approved",
"type": "Boolean",
"displayName": "Approved",
"isNullable": true,
"isSearchable": false,
"isFilter": true,
"isInternal": false
}
]
}
In the above JSON, approved is the field name so I am able to extract schema, but I have a JSON data string as below and want to extract schema from it.
{
"skuId": "1",
"balance": [
{
"warehouseId": "1_1",
"warehouseName": "Main Warehouse",
"totalQuantity": 1000001,
"reservedQuantity": 1,
"hasUnlimitedQuantity": true,
"timeToRefill": null,
"dateOfSupplyUtc": null
}
]
}
In the above example JSON data, warehouseid, warehousename, etc., are fieldname and I need to have those in my schema in c#.
Can anyone please suggest?
create a new class, copy your json data string, and in visual studio click edit -> paste special, and it will create classes that you can deserialize to the way you want.
You are missing the closing ']' so that needs to be addressed first.
If you use a dictionary and need to iterate it :
foreach(KeyValuePair<string, string> entry in myDictionary) { // do something with entry.Value or entry.Key }

Youtube Data v3 Api, Get Request sort

Hey everyone i'm trying to use the v3 Data Youtube API, already have the Request itself and the response looks like this
{
"items": [
{
"snippet": {
"publishedAt": "2016-12-07T16:04:40.472Z",
"displayMessage": "a"
}
}
]
}
The Problem is that i only want the last Comment and not the whole 200(cant be set lower) my first Idea was to Save the whole Response and Compare it to the next one so i know whats new, but that wont really work out
Ok, so from the comments, I gather you are talking about the Live Streaming API.
What you get back are messages, not comments. And yes, as the doc says, "Acceptable values are 200 to 2000, inclusive. The default value is 500." So, you could get the whole 200, and then sort on the timestamp to get the latest message.
How to do that?
As you are doing this in C#, once you have the json string, you need to use some library such as Json.NET. Once you add a NuGet package reference to this, you will need
using Newtonsoft.Json.Linq;
and say your json string is
var json = #"{
""items"": [
{
""snippet"": {
""publishedAt"": ""2016-12-07T16:04:40.472Z"",
""displayMessage"": ""a""
}
}
,
{
""snippet"": {
""publishedAt"": ""2016-12-12T16:04:40.472Z"",
""displayMessage"": ""b""
}
}
]
}";
Then, as described in this documentation, use JObject.Parse to use LINQ to JSON.
var parsedJson = JObject.Parse(json);
JArray items = parsedJson.SelectToken("items") as JArray;
var sortedItems = items.OrderByDescending(item => item["snippet"]["publishedAt"]);
// sortedItems.First() will give you the item with the newest timestamp
Have put all of this at https://dotnetfiddle.net/ubQAZV.
Alternately, you can use JsonConvert if you prefer to deserialize to strongly-typed code.
More about it here.

How to deserialize json with a blank field?

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.

Categories