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 }
Related
I have this JSON that's a list of objects, like this.
"Fields": [
{
"fieldID": 1,
"name": "field"
}
]
When the list is empty, it is sent like this
"Fields": [
{}
]
I read this in as a string and then try to deserialize it using JsonConvert.DeserializeObject<List<T>>(json); where T is the object that matches the field model. When I do this though, I get a new list with one item in it (count = 1 when it should be 0), the same as if I deserialized this JSON.
"Fields": [
{
"fieldID": 0,
"name": null
}
]
How can I avoid or work around this?
First following json does not represent empty list:
"Fields": [
{}
]
An empty list in json should look like following:
"Fields": []
So you should try to fix the json. However, if that's proven to be impossible you can do something like following:
using (JsonDocument document = JsonDocument.Parse(jsonString))
{
JsonElement root = document.RootElement;
var l = root.EnumerateArray().First().ToString();
if(l=="{}")
{
//do something
}
}
What's happening is that you simply parsing the json and enumerate through the list of element and detect if "{}" exists.
Or, you can go with a more complex way which is writing a custom converter which handles such case in the way you want. You can check out the documentation here
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?
I would like to dynamically create c# object based on the the consumed Json. I do not care about this json but simply would like pick out properties that I need.
I dont know if its best practice to use dynamic keyword and based on the created object I can create a whole new json structure.
How can I desearilize nested objects. Example json:
{
'name': 'James',
'Profile': {
'body': {
'id': 'Employee1',
'type': 'Employee',
'attributes': {
props...
},
'job': {
props..
},
'team': [],
},
}
Here is a simple attempt.
var test = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(test.ToString());
I can create object list however when I begin Parent/Child objects I cant seem to get it to work.
Below JSON works fine as an output:
'body': {
'id': 'Employee1',
'type': 'Employee',
'attributes': {
props...
},
'job': {
props..
},
'team': [],
}
Desired Output
{
'name': 'James',
'Profile': {
'body': {
'id': 'Employee1',
'type': 'Employee',
'attributes': {
props...
},
'job': {
props..
},
'team': [],
},
'Profile': {
'body': {
'id': 'Employee2',
'type': 'Employee',
'attributes': {
props...
},
'job': {
props..
},
'team': [],
}
}
How can I deserialize nested objects?
You can use the json class with following this line of code
dynamic data = Json.Decode(json);
You can use JsonConvert:
dynamic myNewObject = JsonConvert.DeserializeObject(json);
And then, you can access json properties like this:
myNewObject.Profile.body.id
No repro. The string is already deserialized. test contains the entire graph. The expected output is produced as long as a valid JSON string is used :
This snippet :
var json=#"{
'name': 'James',
'Profile': {
'body': {
'id': 'Employee1',
'type': 'Employee',
'attributes': {
'a':3
},
'job': {
'a':3
},
'team': [],
},
}";
var x=JsonConvert.DeserializeObject<object>(json);
Console.WriteLiine(x.ToString());
Produces :
{
"name": "James",
"Profile": {
"body": {
"id": "Employee1",
"type": "Employee",
"attributes": {
"a": 3
},
"job": {
"a": 3
},
"team": []
}
}
}
From the comments though, it looks like the actual JSON string isn't a valid JSON string and throws an exception :
I get Newtonsoft.Json.JsonReaderException: 'Additional text encountered after finished reading JSON content: ,. Path '', line 21, position 13.'
This error points to the actual location in the JSON string that caused the problem. Perhaps there's an extra character there? Perhaps the text contains multiple JSON strings instead of one? The following string is not valid JSON - JSON can't have more than one root objects :
{ "a":"b"}
{ "c":"d"}
Logging tools, event processing and analytic software though store multiple JSON strings per file this way because it only needs an append operation, doesn't require parsing the entire text to produce results and makes partitioning easier. That's still invalid JSON though that has to be read and processed one line at a a time.
You many find this described as "streaming JSON", precisely because you can process the data in a streaming fashion. Instead of loading and parsing a 100MB event file, you can load and process a single line at a time eg:
IEnumerable<string> lines=File.ReadLines(pathToBigFile);
foreach(var line in lines)
{
var myObject=JsonConvert.DeserializeObject<someType>(line);
//do something with that object
}
File.ReadLines returns an IEnumerable<string> that only loads a single line on each iteration. Instead of loading the entire 100MB file, only one line is loaded and parsed each time.
I have a JSON document coming from a vendor that looks like this:
{
"content": [{
"name": "Windows 8.1 x64",
"id": "Windows81x64",
"components": {
"Windows81x64": {
"propertyGroups": ["VirtualWindows81x64"],
"dependsOn": [],
"data": {
"provisioning_workflow": {
"fixed": {
"id": "WIMImageWorkflow",
"label": "WIMImageWorkflow"
}
},
"memory": {
"default": 2048,
"min": 2048,
"max": 16384
}
}
}
}
}]
}
Most of this document is fairly easy to deserialize into an object using the typical DataContractSerializer, however, there are a couple of keys/values that I am not sure what the "best practice" might be.
If you look at the "components" key the first key after that one is titled "Windows81x64". This key can change from document to document and it can be any value. It almost should be a 'Name' property of the collection but I can't control that. Furthermore, inside the 'Windows81x64' key there is another property called 'data'. According to the vendor the value of data is 'anonymous.' So, basically it can be anything.
Any ideas on the best way to deserialize this into a custom object when it comes to those parts of the document? Thank you.
You can deserialize dynamic ones as Dictionary<string, object>
Or if you know the value's type you can use Dictionary<string, ValueType> where the key of the dictionary would be the name (in your case Windows81x64)
I want to extract a JSON schema (as defined here) from an object of type dynamic.
This is the best example I could find.
But JSON.NET's Schema Generator needs to look at an actual class/type to be able to generate a schema.
Anyone have any ideas on how I could extract a schema from a dynamic object?
You can still use JSON.NET to extract a JSON schema from dynamic object. You just need an actual object of type dynamic to be able to do that. Try the following sample:
dynamic person = new
{
Id = 1,
FirstName = "John",
LastName = "Doe"
};
JsonSchemaGenerator schemaGenerator = new JsonSchemaGenerator {};
JsonSchema schema = schemaGenerator.Generate(person.GetType());
The generated JSON schema should look like this:
{
"type": "object",
"additionalProperties": false,
"properties": {
"Id": {
"required": true,
"type": "integer"
},
"FirstName": {
"required": true,
"type": [
"string",
"null"
]
},
"LastName": {
"required": true,
"type": [
"string",
"null"
]
}
}
}
If you are using .NET 4.0+ then there is a method System.Web.Helpers.Json.Decode that converts JSON into a dynamic object:
using System.Web.Helpers;
// convert json to a dynamic object:
var myObject = Json.Decode(json);
// or to go the other way and get json from a dynamic object:
string myJson = Json.Encode(myObject);
To reference this assembly you can find it in the Extensions group under Assemblies in Visual Studio 2012.
This should be able solve your problem. If you can include a sample of the JSON it would be clearer.