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.
Related
I am deserializing a json file into C# objects, in this case MTG cards (json from scryfall.com). Previously I solved the problem with MSSQL; I imported the json data into the database with OPENJSON mapping each element I needed to a column with a proper name, and then created a new json file with properties that matched the class I needed in the application.
For properties like arena_id that have only one value, or for arrays that were used as strings (color_identity), it was not an issue, but for arrays such as card_faces (cards that have 2 playable sides) I had to specify which element of the array I wanted to import.
arena_id int '$.arena_id',
...
[color_identity] nvarchar(max) AS JSON,
...
name_front varchar(100) '$.card_faces[0].name',
mana_cost_front varchar(30) '$.card_faces[0].mana_cost',
name_back varchar(100) '$.card_faces[1].name',
mana_cost_back varchar(30) '$.card_faces[1].mana_cost',
From the SQL tailored file I deserialized every object accordingly, but now I'm trying to do it without SQL and with more direct influence as to what goes where.
As mentioned before, for properties that do not need to be deconstructed I know I can just pick the same property name in the class and it gets accepted easily. My problem is with array properties that I should divide into separate properties with different names.
Is it possible in C# to deserialize in a similar way?
I'm thankful for all kinds of hints and tips as I am relatively new to programming with only one year in a training course.
You just need to create a class that properly represents the expected JSON format, EG:
public class MyClass
{
public int Arena_Id { get; set; }
public CardFace[] Card_Faces { get; set; }
}
public class CardFace
{
public string Name { get; set; }
public string Mana_Cost { get; set; }
}
Then deserialize your JSON:
string json = ... // your data
MyClass x = new Newtonsoft.Json.JsonSerializer() // or whichever serializer you want
.DeSerialize<MyClass>(json)
With this deserialized instance of your class, you can then translate it to another class matching the structure you require.
I am guessing that you are simply able to at least call the JSON.
C# does have a good JSON deserialization directive.
// keep the class as close to how it will show up on the JSON
public class MTGCard
{
public string name;
public int manaCost;
...
}
// then you should be able to just
currentCard = JsonSerializer.Deserialize<MTGCard>(jsonString);
The class and the json are close enough you should be able to simply use the Array features pull the cards you need and then just deserialize it on the call based
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.
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.
I have an object, Project, that contains many fields, some complex some not. It is an EF class, so I can't edit it to add attributes.
I just want to generate a JSON object containing 2 of the fields (one int (id) and one string (name))
I'd hate to create another ViewModel just for this...
In my viewmodel I have a List<Project>. Is there a way to use HTML helpers to get a JSON representation of only the properties I choose without using attributes?
Here is an example of the Project class:
public class Project
{
public int Id {get; set; } <-- Serialize this
public string Name { get; set; } <-- Serialize this
public Object AnotherObject [ Get; Set; } <-- Ignore this
....
}
I'd like it to become:
[{"id":"27","name":"test1"},{"id":"34","name":"test2"},{"id":"35","name":"test3"}]
The ultimate goal here to is output the json directly to the view as a var so that it can be used in building a JsGrid.
If there is a way to do it with Html helpers, that would be great.
Thanks!
Json.NET has a great built in ignore feature. If you tag the Property you want to exclude with the [JsonIgnore] attribute, the serializer will not serialize that property.
[JsonIgnore]
public bool IsValid { get; set; }
I am having difficulty writing the appropriate annotations to represent data which is returned from a JSON Get request which returns data like so:
[{"ProductCode":"0129923083091","Description":"DIESEL ","SalesLitres":6058.7347,"SalesValue":6416.2000},{"ProductCode":"0134039344902","Description":"UNLEADED ","SalesLitres":3489.8111,"SalesValue":3695.7100},
...
]
(ellipsis above just indicating that I could have variable number of these items returned)
In my model class (I am using MVVM approach for a Xamarin project but that's not over relevant here) I am using annotations to represent the model attributes
namespace App8.Models
{
public class ReportRow
{
[JsonProperty("ProductCode")]
public string ProductCode { get; set; } = string.Empty;
[JsonProperty("Description")]
public string Description { get; set; } = string.Empty;
[JsonProperty("SalesLitres")]
public double SalesLitres { get; set; } = 0.0;
[JsonProperty("SalesValue")]
public double SalesValue { get; set; } = 0.0;
}
}
I would like to annote another class which shows the container/contained relationship. However, I coming unstuck as there is no JSON attribute to provide in the annotation to represent the "root" of the returned collection.
I'd have no problem mapping the JSON to an object model for any JSON arrays which are named within the returned JSON. In that case I could create another class with a named JSON attribute which contained a C# List but I am trying to provide an appropriate model mapping for JSON which returns a list of items within an unnamed array.
Any ideas how I could approach this?
To deserialize that JSON, use:
JsonConvert.DeserializeObject<List<ReportRow>>(json)
(or any variant you wish, the key here is asking to deserialize a ICollection of ReportRow. It could be your own class implementing ICollection, or any of the builtins)
The same idea follows to JsonTextReader or whatever other means of deserializing JSON.NET offers. Just use a ICollection<YourType> as target type.