Deserializing Some Odd JSON using C# - c#

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)

Related

C# Nested JSON KeyName Duplication

I searched first, and basically I am trying to avoid having to use JObject in C# in favor of ANY Serializer. An excerpt of a large Microsoft Dynamics JSON trace has JSON formed like this
{
"InBlockOStuff" :
{
"type":"Yea You Know What this is",
"values":[
{
"Key":"Target",
"Value":{
"type":"Yea You Know What this is",
"LogicalName":"Thangie",
"Id":"GuidAs String",
"MagicalContent":{
"type":"Yea You Know What this is",
"values":[
{
"Key":"firstname",
"Value":"New Test thangie One"
},
{
"Key":"Thangieid",
"Value":"some stupid Guid like thangie"
}
]
},
"Shaggy":null,
"SubCategory":{
"type":"Yea You Know What this is",
"values":[ ]
},
"Velma":{
"type":"Yea You Know What this is",
"values":[ ]
},
"Scoobie":null,
"KeyAttributes":{
"type":"Yea You Know What this is",
"values":[ ]
}
}
},
{
"Key":"some text",
"Value":true
},
{
"Key":"some text",
"Value":0
}
]
}
}
Notice the repeated instances of the "keys" value and values It is valid Json, the online validators say it is legit, the online generators will additionally create C# classes/objects but I'm sure you instantly see this mess will have two distinctly different "Values" classes. And that doesn't serialize cleanly.
So am I stuck having to learn JObject to get my data out of this mess?
This is just high level excerpt there exists, for example another MagicalContent key with a different set of key values inside of it, just for arguments sake.

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 }

Can I represent my .NET dictionaries as JSON dictionaries in my GraphQL?

When I'm serialising to JSON, I'm used to .NET dictionaries becoming objects with the keys as properties and the values as their values. (The Json.Net docs have a succinct example.)
I'm using GraphQL and struggling to achieve a similar result. My data for this root query is basically a Dictionary<MyEnum,Dictionary<string,string>>. The closest I've got so far is this:
{
"data": {
"outterDict": [
{
"key": "THING_1",
"innerDict": [
{
"key": "key1",
"val": "val1"
},
...
]
},
{
"key": "THING_2",
"innerDict": [
{
"key": "key2",
"val": "val2"
},
...
]
}
]
}
}
But I want it to be closer to this:
{
"data": {
"collection": {
"THING_1": {
"key1": "val1",
...
},
"THING_2": {
"key2": "val2",
...
}
}
}
}
I'm struggling because GraphQL .Net only seems to understand lists, not dictionaries.
It doesn't feel like what I'm trying to do is unreasonable. Letting keys be keys seems right and like the most useful way to share this data (e.g. as suggested by this answer).
Is there a way to do this in GraphQL? Is there a way to do this in GraphQL .Net?
After quite of lot of research, it seems like this isn't in the spec of GraphQL and is therefore unsupported in GraphQL.Net.
GraphQL expects all possible properties (i.e. keys in a map/dictionary) to be known in advance. This means we lose a lot of the value of passing a dictionary at run time.
So although the GraphQL JSON is more verbose than idiomatic JSON, it's like this deliberately.

How to read from Multi-Dimensional dictionary C#

I am trying to figure out a better way to handle this object/dictionary puzzle that I have going on here.
Basically, I am getting a JSON iResponse (rest sharp) and deserializing into a Dictionary. That works fine, but I get a massive dictionary that also contains objects and possibly more dictionarys? I am a little confused.
Here is my code that grabs the response to put into a dictionary:
var TicketInfo = jss.Deserialize<Dictionary<dynamic, dynamic>>(ticketExistsJSON.Content);
This is what I am getting in console:
So this is inside my JiraTicketInfo variable. You can see its full of key value pairs, but inside the value of those key value pairs is another dictionary? In this dictionary contains the key value pairs I want. I specifically only want number 1.
I found a way to finally get it with
Dictionary JiraTicketInfo = TicketInfo["issues"][0]["fields"];
var bumStatus = (object[])JiraTicketInfo["customfield_10004"];
var numStatusDict = (Dictionary)bumStatus[0];
JiraOrg = numStatusDict["name"].ToString();
But I feel like there is a much simpler way to obtain this, but my brain cant seem to understand the multi-dimensional dictionary
Any help would be much appreciated!
I am not even looking for an answer, just a place where to find one. Thank you :)
here is my JSON response:
{
"expand": "names,schema",
"startAt": 0,
"maxResults": 1,
"total": 1,
"issues": [
{
"expand": "customfield_10087.properties,operations,versionedRepresentations,editmeta,changelog,renderedFields",
"id": "18293",
"self": "https://www.myjirahost.com/rest/api/2/issue/18293",
"key": "SS-2991",
"fields": {
"customfield_10070": null,
"customfield_10071": null,
"customfield_10072": null,
"customfield_10073": null,
"customfield_10074": null,
"customfield_10075": null,
"customfield_10089": null,
"customfield_10004": [
{
"id": "99",
"name": "Organization Name B",
"_links": {
"self": "https://www.myjirahost.com/rest/servicedeskapi/organization/99"
}
}
],
"environment": null,
"duedate": null
}
}
]
}
Solved with help from you all using resttosharp website and building out classes:
RootObject JiraIssueObj = JsonConvert.DeserializeObject(ticketExistsJSON.Content);

DataContractJsonSerializer - deserialize to dictionary

I want to deserialize a json that I get as result of a REST query (the json string can not be changed) to a dictionary type.
The json string looks something like this:
{
"collection": {
"useful": true
"attributes": {
"ObjectID": "ObjectID",
"Name": "Name",
"FirstID": "FirstID",
"LastID": "LastID",
"Count": "5",
},
"Type": "Polyline",
"features": [{
"attributes": {
"length": 0.10879009704943393
"time": 0.3822371137674949,
"text": "some text",
"ABC": -2209161600000,
"Type": "SomeType"
}
}]
}
}
I create boolean property for 'useful' and integer for 'count' etc. but I have a problem with the 'attributes'. As you can see, in each section (and per result) I get different 'attributes'.
I need to deserialize them into some generic collection like dictionary or list of KeyValuePair. the problem is, as stated in msdn (here - http://msdn.microsoft.com/en-us/library/bb412170.aspx) "Dictionaries are not a way to work directly with JSON".
How can I do it if so?
My application is silverlight 5, .Net 4, VS 2010.
Thanks in advance!

Categories