I have a REST API from which I get the JSON data back.
The JSON model looks like the following:
{
"Id": "",
"Name": "",
"ExternalId": "",
"Headers": [
{
"Name": "",
"DisplayAt": ""
}
],
"Rows": [
"Array[string]"
],
"NewRows": [
"Array[string]"
],
"DeletedRows": [
"Array[string]"
],
"CompanyId": 0,
"IntegrationKey": ""
}
I've made a Class model that looks like the following:
Imports Newtonsoft.Json
Namespace Models
Public Class Header
<JsonProperty("Name")>
Public Property Name As String
<JsonProperty("DisplayAt")>
Public Property DisplayAt As String
End Class
Public Class DataSource
<JsonProperty("Id")>
Public Property Id As String
<JsonProperty("Name")>
Public Property Name As String
<JsonProperty("Headers")>
Public Property Headers As Header()
<JsonProperty("Rows")>
Public Property Rows As String()()
<JsonProperty("TotalRows")>
Public Property TotalRows As Integer
<JsonProperty("LastUpdated")>
Public Property LastUpdated As DateTime
<JsonProperty("CompanyId")>
Public Property CompanyId As Integer
End Class
Public Class Category
<JsonProperty("DataSource")>
Public Property DataSource As DataSource
End Class
End Namespace
From the array rows I retrieve all my necessary data which is saved in a datatable. Via a BindingSource all the fields are bound to the listbox and all changes are saved to the datatable.
The JSON is deserialized with NewtonSoft.
Now I want to save the changes back to the database via a PUT statement. Therefore I have to serialize the datatable.
I can do that with the following code:
json = JsonConvert.SerializeObject(datatable, Formatting.Indented)
In this case I'm getting only the array from the Rows in a nice JSON format.
My first question is:
How do I serialize the datatable so that I can also pass the ID and externalID in my JSON?
My second question:
Does it updates all the datarows from the database or is it also possible to just update the changed rows?
Related
I want to read a data from Json Response But i am getting Difficulty to get the data.
i want to read this item from Json Response as Shown Below
period, fromDate, dueDate, totalInstallmentAmountForPeriod
Json Response
{
"currency": {
"decimalPlaces": 0,
"inMultiplesOf": 1
},
"loanTermInDays": 92,
"totalPrincipalDisbursed": 100000,
"periods": [
{
"dueDate": [
2022,
7,
8
],
"principalDisbursed": 100000,
"totalActualCostOfLoanForPeriod": 0
},
{
"period": 1,
"fromDate": [
2022,
7,
8
],
"dueDate": [
2022,
8,
8
],
"daysInPeriod": 31,
"totalInstallmentAmountForPeriod": 36035
},
{
"period": 2,
"fromDate": [
2022,
8,
8
],
"dueDate": [
2022,
9,
8
],
"daysInPeriod": 31,
"totalInstallmentAmountForPeriod": 36035
}
],
"mandatorySavings": [
{ "periodId": 0"expectedSavings": 10000.000}]
}
Your JSON is invalid, it looks like there is a missing comma after mandatorySavings -> periodId and expectedSavings.
Visual Studio has a cool feature called Paste JSON as Classes that can be found under Edit > Paste Special > Paste JSON as Classes. Using either Newtonsoft.Json or System.Text.Json, you can tidy the classes up a little bit using decorators so that you can conform to .NET standard naming conventions while still serializing the JSON to the expected values. I also prefer to use IEnumerables over arrays, but the paste JSON as classes uses the latter.
This is how the class definitions would look tidied up a bit:
Public Class Rootobject
<JsonProperty("currency")>
Public Property Currency As Currency
<JsonProperty("loanTermInDays")>
Public Property LoanTermInDays As Integer
<JsonProperty("totalPrincipalDisbursed")>
Public Property TotalPrincipalDisbursed As Integer
<JsonProperty("periods")>
Public Property Periods As IEnumerable(Of Period)
<JsonProperty("mandatorySavings")>
Public Property MandatorySavings As IEnumerable(Of Mandatorysaving)
End Class
Public Class Currency
<JsonProperty("decimalPlaces")>
Public Property DecimalPlaces As Integer
<JsonProperty("inMultiplesOf")>
Public Property InMultiplesOf As Integer
End Class
Public Class Period
<JsonProperty("dueDate")>
Public Property DueDate As IEnumerable(Of Integer)
<JsonProperty("principalDisbursed")>
Public Property PrincipalDisbursed As Integer
<JsonProperty("totalActualCostOfLoanForPeriod")>
Public Property TotalActualCostOfLoanForPeriod As Integer
<JsonProperty("period")>
Public Property Period As Integer
<JsonProperty("fromDate")>
Public Property FromDate As IEnumerable(Of Integer)
<JsonProperty("daysInPeriod")>
Public Property DaysInPeriod As Integer
<JsonProperty("totalInstallmentAmountForPeriod")>
Public Property TotalInstallmentAmountForPeriod As Integer
End Class
Public Class Mandatorysaving
<JsonProperty("periodId")>
Public Property PeriodId As Integer
<JsonProperty("expectedSavings")>
Public Property ExpectedSavings As Integer
End Class
Now all you would need to do is use JsonConvert.DeserializeObject to convert the JSON literal to an instance of your Rootobject class:
Dim conversion = JsonConvert.DeserializeObject(Of Rootobject)(literal)
Fiddle: https://dotnetfiddle.net/Eq88rV
I would like to know how to extract a specific object from a JSON.
I saw most of the problem solved on Stackoverflow before posting this, but there is no one who already talked about this.
I want need to get the slug value from the JSON objects.
Here is my code Get Users From JSON
Imports System
Imports Newtonsoft.Json.Linq
Public Module Module1
Public Sub Main()
Dim myJsonString = New System.IO.StreamReader(New System.Net.WebClient().
OpenRead("https://pastebin.com/raw/z4GZFuF3")).ReadToEnd()
Dim myJObject = JObject.Parse(myJsonString)
For Each match In myJObject("matches")
Console.WriteLine(match("id")("slug"))
Next
End Sub
End Module
And Here is the Output:
Run-time exception (line -1): Error reading JObject from JsonReader.
Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
Stack Trace:
[Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader.
Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.]
at Newtonsoft.Json.Linq.JObject.Load(JsonReader reader, JsonLoadSettings settings)
at Newtonsoft.Json.Linq.JObject.Parse(String json, JsonLoadSettings settings)
at Newtonsoft.Json.Linq.JObject.Parse(String json)
at Module1.Main()
What I have reduced since this error is that the object "matches" does not exist in the JSON text, but I have no idea what I should specify in its place to make this work.
The JSON that can be retrieved from the provided address:
(http://www.stginternational.org/wp-json/wp/v2/users)
is an array of Objects.
It can be parsed using JArray.Parse(), but I suggest to deserialize this JSON as .Net classes: it's much easier to handle.
The JSON's base object (each object in the array) is defined like this:
{
"id": 1,
"name": "drall",
"url": "",
"description": "",
"link": "http://www.stginternational.org/author/drall/",
"slug": "drall",
"avatar_urls": {
"24": "http://1.gravatar.com/avatar/dc6dd0ef71784957b629e124f19364cb?s=24&d=mm&r=g",
"48": "http://1.gravatar.com/avatar/dc6dd0ef71784957b629e124f19364cb?s=48&d=mm&r=g",
"96": "http://1.gravatar.com/avatar/dc6dd0ef71784957b629e124f19364cb?s=96&d=mm&r=g"
},
"meta": [],
"_links": {
"self": [
{
"href": "http://www.stginternational.org/wp-json/wp/v2/users/1"
}
],
"collection": [
{
"href": "http://www.stginternational.org/wp-json/wp/v2/users"
}
]
}
}
It can be represented by these .Net classes:
Public Class UserObject
Public Property Id As Long
Public Property Name As String
Public Property Url As String
Public Property Description As String
Public Property Link As Uri
Public Property Slug As String
<JsonProperty("avatar_urls")>
Public Property AvatarUrls As Dictionary(Of String, Uri)
Public Property Meta As List(Of Object)
<JsonProperty("_links")>
Public Property Links As Links
End Class
Public Class Links
Public Property Self As List(Of LinkCollection)
Public Property Collection As List(Of LinkCollection)
End Class
Public Class LinkCollection
Public property Href As Uri
End Class
With this model, you can simply use JsonConvert.DeserializeObject(), specifying the Type to deserialize to.
As mentioned, this is an Array or List of objects, where the base object is an UserObject, so you can specify a List(Of UserObject) :
Dim json = JsonConvert.DeserializeObject(Of List(Of UserObject))(json)
You can then access the class object as usual:
Imports System.Net
Imports Newtonsoft.Json
Dim users As List(Of UserObject) = Nothing
Using client As New WebClient()
Dim json = client.DownloadString([The URL])
users = JsonConvert.DeserializeObject(Of List(Of UserObject))(json)
End Using
If users IsNot Nothing Then
For Each user In users
Console.WriteLine(user.Slug)
Console.WriteLine(user.Links.Self(0).Href)
Console.WriteLine(user.Links.Collection(0).Href)
For Each avatar In user.AvatarUrls
Console.WriteLine($"Key: {avatar.Key}, Value: {avatar.Value}")
Next
Next
End If
In case you just want one of the properties (slug, in this case), you can use JArray.Parse() to parse the JSON and read the property value directly:
Using client As New WebClient()
Dim json = client.DownloadString([The URL])
Dim users = JArray.Parse(json)
For Each user As JToken In users
Console.WriteLine(user("slug"))
Next
End Using
While Jimi's answer is preferable because it deserializes the JSON into a strongly typed object, here is an alternative since you only care about getting a single property from the array of objects.
It does the following three steps:
Get the JSON from the endpoint
Convert the JSON literal into JArray
Use LINQ to get just the Slug item of each object in the array
Dim myJsonString = New System.IO.StreamReader(New System.Net.WebClient().OpenRead("http://www.stginternational.org/wp-json/wp/v2/users")).ReadToEnd
Dim arrayOfObjects = JArray.Parse(myJsonString)
Dim arrayOfSlugs = From jsonObject In arrayOfObjects Select jsonObject.Item("slug")
Example: Live Demo
My Spring REST controller needs to map an object parameter that looks like this:
{
"batchId": 43091,
"domain": "XX",
"code": "XXX",
"effectiveDate": "2020-02-13",
"status": "Y",
"result": [{"ruleName":"name",...]}]
}
I'm having trouble coming up with the DTO to convert this data into. What I have so far looks like this:
#Data
#NoArgsConstructor
#EqualsAndHashCode
public class ValidationResult {
private String result;
private String status;
private String batchId;
private String domain;
private String code;
private String effectiveDate;
}
But result, which contains the embedded JSON, is always null. I don't care about that JSON being mapped, as I'm storing it as a JSON type in the database (Postgresql). But what Java type do I need to declare it to be to get the controller to convert it? I tried making it a javax.json.JsonObject, but that failed.
What we always do with those json inputs is to map those to specific classes. Which means, in your case, result could be a class which itself contains the given fields "ruleName" and their types. Then your Validaton Result containts a private Result result. If naming conventions are quite right the used mapper will be able to convert and map the response to the class and its properties.
I try to get the values from the basic section in the following json result
{
"responseCode": "Ok",
"responseMessage": "",
"ssnStatus": "Active",
"basic": {
"firstName": "Testnamn",
"givenName": "Gettnamn",
"surName": "Testname",
"middleName": null,
"lastName": "Lastname",
"co": null,
"street": "Teststreet lgh 1202",
"zipCode": "92609",
"city": "Stad"
},
"phoneNumbers": {
"phoneNumbers": []
},
"ssnStatusBlock": null
}
I can get the first level (ssnStatus) with the code below, but how do I get the firstName, givenName etc?
Dim post As Post = JsonConvert.DeserializeObject(Of Post)(exampleJson)
Dim ssnStatus As String = post.ssnStatus
and
Public Class Post
Public Property ssnStatus As String
End Class
You are missing the properties and classes definition for all the other membersof the JSON object.
Create a new class file in your Project. Give it a name that properly describe the JSON usage,
add the Imports Newtonsoft.Json import,
copy a sample of the JSON object that describes the JSON structure (the one you have here is good),
position the caret inside the new class definition,
see the Visual Studio menu: Edit -> Paste Special -> Paste JSON as classes
Visual Studio will create all the classes and properties needed to handle the JSON object you selected.
Note: With more complex classes, it may happen that the result Visual Studio produces is not exactly what you require. In this case, try one of the specialized WebSites that provide a free conversion service:
Json Utils (VB.Net, C#, Java, Javascript, more...)
QuickType (C#, C++, Java, Javascript, Python, Go, more...)
json2csharp (C#)
JSON Formatter (JSON formatting and validation)
The new root class definition will be named Rootobject. Change this name as needed,
to make it more clear what the class is used for.
This is the class definition that Visual Studio creates with the JSON object in your question.
I created a class Project class named MyWebSitePost, created the JSON bject class definition as previously described, I then renamed the default master class Post, replacing the default Rootobject name:
Public Class MyWebSitePost
Public Class Post
Public Property responseCode As String
Public Property responseMessage As String
Public Property ssnStatus As String
Public Property basic As Basic
Public Property phoneNumbers As Phonenumbers
Public Property ssnStatusBlock As Object
End Class
Public Class Basic
Public Property firstName As String
Public Property givenName As String
Public Property surName As String
Public Property middleName As Object
Public Property lastName As String
Public Property co As Object
Public Property street As String
Public Property zipCode As String
Public Property city As String
End Class
Public Class Phonenumbers
Public Property phoneNumbers() As Object
End Class
End Class
You can then use the code you already have to access all the other properties:
(Some Properties type may have been set to Object; modify as
required).
Dim JsonPost As Post = JsonConvert.DeserializeObject(Of Post)(exampleJson)
Dim ssnStatus As String = JsonPost.ssnStatus
Dim FirstName As String = JsonPost.basic.firstName
and so on.
Note:
As you can see, all properties have the default name, as defined in the JSON object. Some properties names are not really adeguate to describe thier content. For example the co property is probably the Country name. To change the property name, you can use the <JsonProperty> attribute, which references the JSON object original name and use a custom name for the Property:
'(...)
<JsonProperty("co")>
Public Property Country As Object
'(...)
You can then access this Property using the custom name:
Dim CountryName As String = JsonPost.basic.Country
I'm trying to generate some JSON that looks like this:
{
"#type": "MessageCard",
"sections": [
{
"activityTitle": " Request",
"facts": [
{
"name": "name1",
"value": "Value"
},
{
"name": " Date:",
"value": "Value Date"
}
],
"text": "Some Test."
}
],
"potentialAction": [
{
"#type": "ActionCard",
"name": "Add a comment",
"inputs": [
{
"#type": "TextInput",
"id": "comment",
"isMultiline": true
}
]
}
]
}
I performed a paste special into VS and it generated the class structure for me as such:
Public Class MessageCard
Public Property type As String
Public Property context As String
Public Property summary As String
Public Property themeColor As String
Public Property sections() As Section
Public Property potentialAction() As Potentialaction
End Class
I'm trying to add the sections to the object as such:
Dim m as New MessageCard
Dim s As New List(Of Section)
s.Add(s1)
s.Add(s2)
m.sections = s
The compiler complains that it cannot convert a list of Sections into a Section. Did the class get generated incorrectly, or am i constructing it incorrectly?
First, your JSON is not quite complete and the Classes you show wont create that JSON.
As posted, that JSON simply shows a Sections and potentialAction class which are not related in any way. An enclosing [ ... ] is needed to represent the MessageCard class containing the two of them.
[{
"#type": "MessageCard",
...
}]
Next, the class you have shows all sorts of things not present in the JSON: context, summary and themeColor for instance. I assume those might be missing for brevity, but it is confusing. There is also 2 other Types missing which are in the JSON, Fact and Input.
Corrected, the classes should be:
Public Class MsgCard
<JsonProperty("#type")>
Public Property ItemType As String
Public Property sections As List(Of Section)
Public Property potentialAction As List(Of Potentialaction)
Public Sub New()
sections = New List(Of Section)
potentialAction = New List(Of Potentialaction)
End Sub
End Class
Public Class Section
Public Property activityTitle As String
Public Property facts As Fact()
Public Property text As String
End Class
Public Class Fact
Public Property name As String
Public Property value As String
End Class
Public Class Potentialaction
<JsonProperty("#type")>
Public Property ActionType As String
Public Property name As String
Public Property inputs As Input()
End Class
Public Class Input
<JsonProperty("#type")>
Public Property InputType As String
Public Property id As String
Public Property isMultiline As Boolean
End Class
Notes
You did not specify a JSON serializer, so this is prepared to JSON.NET as recommended by Microsoft.
#type is an illegal property name, so the JsonProperty attribute is used to create an alias. I also used less confusingly redundant names.
You may want to change Fact and Input to List(Of T) if you will be creating and pushing them into the class object as well.
Finally, for the actual question you asked, most of the automatic class generators have trouble with arrays (even VS).
Public Property sections() As Section
' should be:
Public Property sections As Section()
That simply declares that sections will be an array, it does not create the array. Normally this is not a problem because the Serializer/Deserializer will create the array. To allow code external to the class to add to them, you probably want to use a List as the classes above do, then create the instance in the constructor:
Public Sub New()
sections = New List(Of Section)
potentialAction = New List(Of Potentialaction)
End Sub