C# JSON.Net place items in one list into another - c#

I have a JSON that I am creating in C# using JSON.net. My object contains a meta and data sections. The data section is a JSON Array and contains other JSON Array's in it. The problem I have is my main data entity. Right now I have all the data for that entity written in a list. The problem is I need to extract all that data from the list and move it up to the data level. Here is what I am outputting right now:
{
"meta":
{
//meta info here. This is static and formatted correctly.
}
"data":
[
{
"main record data:"
[
{
//Here is dynamically created data that I need to move.
}
]
}
]
}
My object in C# has the main class which defines the meta and data sections of my JSON. The data section is a List<DataModel>. Within that are all my other lists to setup each section that is included in the data section of the JSON. The list I need is an organization list. Here is the the condensed model:
public class JSONModel
{
[JsonProperty(Order = 1)]
public EntityProperties meta { get; set; }
[JsonProperty(Order = 2)]
public List<DataModel> data { get; set; }
}
public class DataModel
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<EntityProperties> org { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<EntityProperties> addresses { get; set; }
}
What I need to output is this:
{
"meta":
{
//meta info here. This is static and formatted correctly.
}
"data":
[
{
//Here is dynamically created data from the org list.
}
]
}
The tool I am using is SCRIBE Online and this is a custom connector I am building. That is where the <EntityProperties> comes from. That is what they provide to me and then I just pass them into my list and it puts them into the proper JSON format with label: data. If the org entity was going to have static fields like the meta, then it would be simple in my opionion. I am hoping that I can just pull the data into a JObject and then insert them back in at the top of my data section, but this is my first go with JSON.net and I am not sure if I am on the right path. Any input would be greatly appreciated.

Instead of having a List<DataModel> you should just have a single object of DataModel.
If you want to organize your "org" and "address" into single object instances then create a class that holds a reference to a single object of each, and then create a list of that class in your DataModel class.

Related

Need help deserializing C# / .NET 6 into seperate objects

I am attempting to use JsonSerializer.Deserialize() from System.Text.JSON in .NET 6.
I have no control over the format of the JSON.
I have used it successfully in the past but now the data I need to consume is more complicated (but not VERY complicated). I am assuming that I am simply describing my data incorrectly.
I have tried several things.... but the description below is the only way so far that I could consume the data at all.
I think my biggest problem is that I am trying to use the wiz-bang "Paste Special -> Paste JSON as Classes" without really understanding how to form my classes for serialization/deserialization.
Here is a simple example of the JSON I am trying to consume:
[
{
"version": "1.0b",
"sub_version": "x.y.barf"
},
{
"somestring": "I am a string",
"isCool": false,
"a_cool_array": [
"bob",
"jill",
"pete"
]
}
]
If I use the whiz-bang "Paste Special" tool, I get the following generated for me.
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string version { get; set; }//<-- I need these to remain in their own object
public string sub_version { get; set; }//<-- I need these to remain in their own object
public string somestring { get; set; }
public bool isCool { get; set; }
public string[] a_cool_array { get; set; }
}
Here is the problem that I have.
The whiz-bang tool put my first object (with one version strings) and second (more complicated) object into the same object.
If I use a call like this:
var deserializedJSON = JsonSerializer.Deserialize<List<Class1>>(myJSONTextHere);
I end up with two objects in the list.
The first one has the versions filled out, the second one only has the other fields filled out.
This all makes sense to me but I don't know how to get around the problem.
I need these objects to model the JSON and I need them to save back in the same format when I re-serailize the modified classes elsewhere. This isn't my exact problem as I have simplified it for the question.
I have found one way around this problem.
It is ugly but seems to work. I hate that my code has to know about the data it is manipulating.
I used the actual JSON DOM to split the two disparate classes into individual JSON objects, then used the class de-serializer to load the individual objects into their given types.
In the following example, I am not checking anything.. I happen to know the order of the objects. I could check the raw JSON to make sure it was what I was looking for. In this case, I don't need to.
So, instead of taking the class structure as pasted by the super spiffy "Paste Classes from JSON" thingamajigger.. I split the classes myself.
Like this:
public class VersionClass
{
public string version { get; set; }
public string sub_version { get; set; }
}
public class DataClass
{
public string somestring { get; set; }
public bool isCool { get; set; }
public string[] a_cool_array { get; set; }
}
Then, I can load the JSON into the objects I need like this:
using var jsonDoc = JsonDocument.Parse(jsonText);
var versionClass = jsonDoc.RootElement[0].Deserialize<VersionClass>();
var dataClass = jsonDoc.RootElement[1].Deserialize<DataClass>();
I hope this helps someone having the same problem.
Your json needs to look like this:
{
"class1": [
//more json
],
"class2": [
//more json
]
}
Then you will have:
public class RootObject
{
// class1 and 2 in here
}
public class Class1
{
}
public class Class2
{
}

Insert nested JSON in 2 SQL tables in C#

I have the following sample JSON and am trying to insert it into 2 tables called Order and OrderLines. There could be 100 records coming in at a time in the form of JSON array.
How do I deserialize it and insert rows from this in 2 SQL tables viz order and orderlines?
{
"OrderID":"123466",
"WebOrderID":"0",
"PersonID":"13",
"BillToAddressType":"Business Address",
"ShipToAddressType":"Temp Address",
"OrderLineItems":
[
{
"ProductID":"123",
"Quantity":"1",
"Price":"50.00",
"BadgeLastName":"BLName",
"BadgeFirstName":"BFName",
"BadgeCompanyName":"BCompany",
"OrderLinePromo":"",
"CourseInfo":[{"CourseID":"2","ClassID":"1"}],
},
{
"ProductID":"233",
"Quantity":"1",
"Price":"50.00",
"BadgeLastName":"",
"BadgeFirstName":"",
"BadgeCompanyName":"",
"OrderLinePromo":"CheapBookDeal"
}
]
}
Create an object class in c#, set the properties to the names in json file, and deserialize the json into the class
public class ClassName {
public int OrderId { get; set; }
public int WebOrderId { get; set; }
public int PersonId { get; set; }
etc......
}
Reference Newtonsoft.Json library. Then deserialize
var values = Newtonsoft.Json.JsonConvert.DeserializeObject<ClassName>(json);
Now for debugging create an instance of the class and step over every property to ensure the values are correct
ClassName newObject = new ClassName();
newObject.OrderId = values.OrderId;
newObject.WebOrderId = values.WebOrderId;
newObject.PersonId = values.WebOrderId;
etc........
Depending on the fields in the json file, you may need to specify the names in the c# class, just above each property in the class just include the [JsonProperty("JsonFieldName")] attribute in case it happens to be case sensitive and c# can't read it into the class.
Create . Net class to set Json data. And deserialize Json data into class using newtonsoft.
Use Newtonsoft.Json from NUGET Package Manager.
If the JSON always has the same properties, then create a class which also has the same data model. This allows you to deserialize it really easily with a call to Newtonsoft.Json.JsonConvert:
T obj = JsonConvert.DeserializeObject<T>(json);
Where T is your C# class.

How can I serialize this Json using my model class?

I have having a problem how to get the empty list and define the properties and set the values in a static method.
FYI : I am also using the same properties id and parentID in another payload that is not a List..
//Here is the json I have
[
{
"id": 1,
"parentId": 4
}
]
//Here is my model class, my static method "Payload" and the properties of Json
public class Model
{
public int id { get; set; }
public int parentId { get; set; }
public static Model Payload()
{
return new Model
{
//How to get define the List here and set the values
}
}
}
The json you have is a List so, with Newtonsoft.Json, you can deserialize to a list.
var myModels = JsonConvert.DeserializeObject<List<Model>>(jsonString);
If the json string is empty "[]", it will create an empty list (not sure if that's what you were asking about the empty list of Model).
To convert the list to string:
var stringPayload = JsonConvert.SerializeObject(myModels);
What is your goal exactly ? You just want to load a model from a JSON string ? If not, what is this list exactly ? I think you should look at this : https://www.newtonsoft.com/json
It's a very popular library for manipulate JSON and data model related to it.

Deserializing Repeating Dictionaries from JSON

I'm trying to de-serialize a large JSON file using JSON.net. I've been unable to de-serialize the nested dictionaries inside this file. The name of the object containing these dictionaries repeats thousands of times inside the file. The code I provided is a small, shortened version of the file I'm dealing with to show an example of these repeating nested dictionaries. I'm looking for a solution to de-serializing the contents of thousands of "image_uris" into classes I suppose, such that I can access the "small", "medium", and "large" keys and values from each "image_uris" object.
[
{
"object":"card",
"id":"789",
"image_uris":
{
"small":"https://img...98713",
"medium":"https://img...89712",
"large":"https://img...97123",
}
},
{
"object":"card",
"id":"654",
"image_uris":
{
"small":"https://img...43243",
"medium":"https://img...26267",
"large":"https://img...00812",
}
},
{
"object":"card",
"id":"091",
"image_uris":
{
"small":"https://img...98760",
"medium":"https://img...92331",
"large":"https://img...87690",
}
}
]
I've been working in the Unity Game Engine, with C#, with JSON.net. I have tried using http://json2csharp.com/ by feeding it the entire JSON file. It spits out ~1700 lines of code with implementation instructions commented at the top. I'm not sure how to access all the generated classes and data in those classes by following those instructions. Those instructions are as follows:
// <auto-generated />
//
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
// using QuickType;
//
// var scryfallDefaultCards = ScryfallDefaultCards.FromJson(jsonString);
Not sure what the problem is but I just copy pasted your JSON snippet into the same site you went to and got this:
public class ImageUris
{
public string small { get; set; }
public string medium { get; set; }
public string large { get; set; }
}
public class RootObject
{
public string #object { get; set; }
public string id { get; set; }
public ImageUris image_uris { get; set; }
}
But your JSON is an array and you should just deserialize like this:
var result = JsonConvert.DeserializeObject<List<RootObject>>(jsonString);
It should work the same using your larger JSON string

Deserializing JSON using C#

Finding some difficulty in sourcing information in trying to deserialize JSON in C#.
I have results from Google custom search returned in JSON format. I just want to check through my steps and establish the order in trying to deserialize it. Is this right?
I need to create classes to match
the JSON format. Kind of like a
creating schema file.
Use the JavaScriptSerializer() class and
deserialize method to extract the
relevant bits.
One of the issues I think I am going to run into is that I don't require all of the data returned but only the html links. How can I achieve that?
UPDATE
I have updated my question with the following JSON snippet and C# code. I want to output the string 'links' to console but it doesn't seem to be working. I think I am defining my classes wrongly?
JSON from Google Custom Search
handleResponse({
"kind": "customsearch#search",
"url": {
"type": "application/json",
"template": "https://www.googleapis.com/customsearch/v1?q\u003d{searchTerms}&num\u003d{count?}&start\u003d{startIndex?}&hr\u003d{language?}&safe\u003d{safe?}&cx\u003d{cx?}&cref\u003d{cref?}&sort\u003d{sort?}&alt\u003djson"
},
"queries": {
"nextPage": [
{
"title": "Google Custom Search - lectures",
"totalResults": 9590000,
"searchTerms": "lectures",
"count": 1,
"startIndex": 2,
"inputEncoding": "utf8",
"outputEncoding": "utf8",
"cx": "017576662512468239146:omuauf_lfve"
}
],
"request": [
{
"title": "Google Custom Search - lectures",
"totalResults": 9590000,
"searchTerms": "lectures",
"count": 1,
"startIndex": 1,
"inputEncoding": "utf8",
"outputEncoding": "utf8",
"cx": "017576662512468239146:omuauf_lfve"
}
]
},
"context": {
"title": "Curriculum",
"facets": [
[
{
"label": "lectures",
"anchor": "Lectures"
}
],
[
{
"label": "assignments",
"anchor": "Assignments"
}
],
[
{
"label": "reference",
"anchor": "Reference"
}
]
]
},
"items": [
{
"kind": "customsearch#result",
"title": "EE364a: Lecture Videos",
"htmlTitle": "EE364a: \u003cb\u003eLecture\u003c/b\u003e Videos",
"link": "http://www.stanford.edu/class/ee364a/videos.html",
"displayLink": "www.stanford.edu",
"snippet": "Apr 7, 2010 ... Course materials. Lecture slides · Lecture videos (2008) · Review sessions. Assignments. Homework · Reading. Exams. Final exam ...",
"htmlSnippet": "Apr 7, 2010 \u003cb\u003e...\u003c/b\u003e Course materials. \u003cb\u003eLecture\u003c/b\u003e slides · \u003cb\u003eLecture\u003c/b\u003e videos (2008) · Review sessions. \u003cbr\u003e Assignments. Homework · Reading. Exams. Final exam \u003cb\u003e...\u003c/b\u003e",
"cacheid": "TxVqFzFZLOsJ"
}
]
}
);
C# Snippet
public class GoogleSearchResults
{
public string link { get; set; }
}
public class Program
{
static void Main(string[] args)
{
//input search term
Console.WriteLine("What is your search query?:");
string searchTerm = Console.ReadLine();
//concantenate the strings using + symbol to make it URL friendly for google
string searchTermFormat = searchTerm.Replace(" ", "+");
//create a new instance of Webclient and use DownloadString method from the Webclient class to extract download html
WebClient client = new WebClient();
string Json = client.DownloadString("https://www.googleapis.com/customsearch/v1?key=My Key&cx=My CX&q=" + searchTermFormat);
//create a new instance of JavaScriptSerializer and deserialise the desired content
JavaScriptSerializer js = new JavaScriptSerializer();
GoogleSearchResults results = js.Deserialize<GoogleSearchResults>(Json);
Console.WriteLine(results);
//Console.WriteLine(htmlDoc);
Console.ReadLine();
}
}
Thanks
I use your #2 approach: deserialize with the JavaScriptSerializer.
This is what I do to deserialize a response from Facebook:
// get the id for the uploaded photo
var jss = new JavaScriptSerializer();
var resource = jss.Deserialize<Facebook.Data.Resource>(responseText);
....where Facebook.Data.Resource is defined like this:
namespace Facebook.Data
{
public class Resource
{
public string id { get; set; }
}
}
The responseText that I am deserializing from looks like this:
{"id":"10150111918987952",
"from":{"name":"Someone",
"id":"782272221"},
"name":"uploaded from Cropper. (at 12\/15\/2010 7:06:41 AM)",
"picture":"http:\/\/photos-f.ak.fbcdn.net\/hphotos-ak-snc4\/hs817.snc4\/69790_101501113333332_782377951_7551951_8193638_s.jpg",
...
But since I have only one property defined in the Resource class, I only deserialize that. Define the fields in your class that you want to deserialize.
It works to use inheritance, of course. You can define your data classes like this:
namespace Facebook.Data
{
public class Resource
{
public string id { get; set; }
}
public class Person : Resource
{
public string name { get; set; }
}
}
...and then you can deserialize a Person object.
EDIT
Ok, given the sample json you provided in the updated question, here's how I wrote the classes to hold the response:
public class GoogleSearchItem
{
public string kind { get; set; }
public string title { get; set; }
public string link { get; set; }
public string displayLink { get; set; }
// and so on... add more properties here if you want
// to deserialize them
}
public class SourceUrl
{
public string type { get; set; }
public string template { get; set; }
}
public class GoogleSearchResults
{
public string kind { get; set; }
public SourceUrl url { get; set; }
public GoogleSearchItem[] items { get; set; }
// and so on... add more properties here if you want to
// deserialize them
}
And here's the C# code to deserialize:
// create a new instance of JavaScriptSerializer
JavaScriptSerializer s1 = new JavaScriptSerializer();
// deserialise the received response
GoogleSearchResults results = s1.Deserialize<GoogleSearchResults>(json);
Console.WriteLine(s1.Serialize(results));
Some comments:
The toplevel class to hold the search result is called GoogleSearchResults.
The first property in the GoogleSearchResults class is kind, corresponding to the first named property in the json object. You had link which isn't going to work, because link is not the name of a top-level property in that json object. There are properties lower in the hierarchy of your json named "link" but JavaScriptSerializer won't pull out those lower level things into the higher level.
The next property in my GoogleSearchResults class is of type SourceUrl. This is because the url property in the json is not a simple string - it is a json object with two properties, each with a string value. So SourceUrl as a class in C# gets two string properties, each with the appropriate name to deserialize one of those named properties.
the next property in the GoogleSearchResults class is called "items" so that it can deserialize the items dictionary from your json. Now items, as the name suggests, is an array in the json, as denoted by the square bracket around its value. This means there can be more than one item, although in your case there is just one item. So this property in C# must be an array (or collection). Each item in the json result is not a simple string, so, once again, as we did with SourceUrl, we need to define a holder class to deserialize the item object: GoogleSearchItem. This class has a bunch of simple string properties. The properties in the C# class could also be of type int or some other type, if that's what the json requires.
finally, when printing out the result, if you just call Console.WriteLine(result) you will see the result of the ToString() method that is implicitly invoked by Console.WriteLine. This will merely print the name of the type, in this case is "GoogleSearchResults", which is not what you want, I think. In order to see what's in the object, you need to serialize it, as I've shown. In the output of that, you will see only the values of things you deserialized. Using the classes I provided, the result will have less information than the original, because I didn't provide properties in the C# class corresponding to some of the json properties, so those weren't deserialized.
You could take a look at Json.NET and its LINQ support to create and query JSON. By crafting a nice LINQ query you will get only the stuff you need (you can select, group by, count, min, max, whatever you like).
http://msdn.microsoft.com/en-us/library/bb412170.aspx
http://msdn.microsoft.com/en-us/library/bb410770.aspx
Pull out the property you need after you have converted the JSON representation to a type in your C# app. I don't think there's a way to extract only one property from the JSON representation before you have converted it (though I am not sure).

Categories

Resources