JSON serialization technicalities in VB.NET - json

What is the difference between the following serialization methods?
First Method
JsonConvert.SerializeObject(list or datatable)
and the output is
i.e. (3) [Object, Object, Object]
Second Method
Dim parent = Prtdata
Dim lGridColumns = New With {
Key .data = parent
}
Dim Setting = New JsonSerializerSettings
Setting.PreserveReferencesHandling = PreserveReferencesHandling.Objects
Dim jsonObject = JsonConvert.SerializeObject(lGridColumns, Formatting.Indented)
Return jsonObject
and its output is
{
"data": [
{
"RecID": 2383,
"PrtStatus": 0,
"PtFilenum": 15090248,
"PrtFilenum": 13090701,
"FullName": "asdasd",
"DOB": "04 Oct 1985"
},
{
"RecID": 3387,
"PrtStatus": 1,
"PtFilenum": 15090248,
"PrtFilenum": 15120996,
"FullName": "marwam mohmmad saleem",
"DOB": "24 May 2017"
},
{
"RecID": 3388,
"PrtStatus": 1,
"PtFilenum": 15090248,
"PrtFilenum": 170227111,
"FullName": "asd dsf as a",
"DOB": "27 Feb 2017"
}
]
}
why the output looks different in the browser console?

As the first comment, you can find a Serialization Guide on the website of NewtonSoft.json, in my answer I just provide a more elaborate version of my comment earlier.
The first scenario, where you are serializing something implemented IEnumerable (eg: list, array), will be represented by an array in Json, eg:
[{ "property": "value", "id": 0 }, {"property": "value", "id": 1}]
For the second scenario, you are doing several things differently, for example you are providing the PreserveReferencesHandling in the JsonSerializerSettings which would also preveserve any references made in the objects you are serializing, eg:
[{"$id": 1, "title": "item1"}, {"$id": 2, "title": "item2", "previous": { "$ref": 1 }]
This would make sure that when deserialized, the second object would contain a reference to the first object, inside the property previous.
Another thing you are doing differently is providing the Formatting.Indented, which will create a more reader friendly json document, having line breaks and indentation. The previous Json would then become something similar to this:
[{
"$id": 1,
"title": "item1"
},
{
"$id": 2,
"title": "item2",
"previous": {
"$ref": 1
}
}]
And, the last big difference is that in the last example, you are serializing a single object, cause it's public properties to be serialized, eg:
{
"data": [
...
]
}
Where data is a property on the object you are serializing.

Related

deserialize json into vb.net class with conditional definition

I am an intermediate programmer and am trying to find a solution to a JSON deserialize issue in vb.net. I'm working some product updates with an API (not mine) in which I have to get the product, deserialize it, change some values, and post an update.
I have built out a bunch of vb.net classes to handle the deserialize (newtonsoft.json) of a JSON doc and for the most part works great. However, I ran into a situation on some products where the object could be defined one of two ways depending on the value of a particular json object.
Here is a snippet of the JSON:
"PriceGrids": [
{
"IsBasePrice": false,
"PriceConfigurations": [
{
"Criteria": "Imprint Method",
"Value": [
"SILKSCREEN"
]
}
]
},
{
"IsBasePrice": true,
"PriceConfigurations": [
{
"Criteria": "Size",
"Value": [
{
"Attribute": "Length",
"Value": "25",
"Unit": "cm"
},
{
"Attribute": "Width",
"Value": "7.5",
"Unit": "cm"
},
{
"Attribute": "Height",
"Value": "14.5",
"Unit": "cm"
}
]
}
]
}
So Value has two definitions depending on the IsBasePrice value (true/false). I currently have Value defined in the class as below.
Private _Value As New List(Of String)
Public Property Value() As List(Of String)
Get
Return _Value
End Get
Set(value As List(Of String))
_Value = value
End Set
End Property
This, of course, fails when it isn't a list of string(s). I can't find an example anywhere of handling this. Is it even possible in vb.net to handle a conditional object definition based on the Json provided?

jdbcTemplate - Convert data from JSON column

Tools: Spring Booot v2.1.3.RELEASE, MySQL 5.7
I have table with column of type JSON named "properties".
I use jdbcTemplate.queryForList(sql) method to read from this table.
Rest service returns something like this:
[
{
"id": 1,
"name": "users",
"properties": "{\"prop1\": \"value1\"}",
"description": "smpl descr1",
"log_enabled": false
},
{
"id": 2,
"name": "members",
"properties": null,
"description": "sample description 2",
"log_enabled": true
}
]
As you can see the "properties" object is type of String.
How to force jdbcTemplete to convert data from JSON column into JSON instead of String?
Expected result:
[
{
"id": 1,
"name": "users",
"properties": {
"prop1": "value1"
},
"description": "smpl descr1",
"log_enabled": false
},
{
"id": 2,
"name": "members",
"properties": null,
"description": "sample description 2",
"log_enabled": true
}
]
I am sorry that JdbcTemplete does not have such function. You have to convert the JSON string to the java object by yourself using your favourite JSON library.
For example , in case of Jackson , you can convert any JSON string to a Map using:
ObjectMapper mapper = new ObjectMapper();
String json = "{\"prop1\": \"value1\" , \"prop2\": 123}";
Map<String,Object> result = mapper.readValue(json,new TypeReference<Map<String,Object>>() {});
result.get("prop1") // "value1"
result.get("prop2") // 123

Ruby: How to parse json to specific types

I have a JSON that I want to parse in Ruby. Ruby is completely new to me, but I have to work with it :-)
Here is my litte snippet, that should do the parsing:
response = File.read("app/helpers/example_announcement.json")
JSON.parse(response)
this works pretty fine. The only downside is, I do not know the properties at the point where I use it, it is not typesafe. So I created the objects for it
class Announcements
##announcements = Hash # a map key => value where key is string and value is type of Announcement
end
class Announcement
##name = ""
##status = ""
##rewards = Array
end
And this is how the json looks like
{
"announcements": {
"id1" : {
"name": "The Diamond Announcement",
"status": "published",
"reward": [
{
"id": "hardCurrency",
"amount": 100
}
]
},
"id2": {
"name": "The Normal Announcement",
"players": [],
"status": "published",
"reward": []
}
}
}
So I tried JSON parsing like this
response = File.read("app/helpers/example_announcement.json")
JSON.parse(response, Announcements)
But this is not how it works^^can anybody help me with this?

Render Nested json objects in React Native

In my render() method i need to parse nested json objects. See the portion of render and json structure below.
I access Last Name with {params.name_last}.
How will i access items under team, like team.name_first
render() {
let { params } = this.props.navigation.state
<Text>{params.name_last}</Text>
}
[
{
"id": 1,
"name_first": "Name first 1",
"name_middle": "",
"name_last": "Name last 1",
"name_suffix": "",
"phone": "888-8888",
"fax": "888-8888",
"updated_at": "2015-11-02T21:42:42.000Z",
"team": [
{
"id": 16,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 28,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 29,
"name_first": "aaa ",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
}
]
}
]
Since team is an array, you need to either access a specific entry in the array, or iterate over the entire thing.
To reach a specific property in the nested array entry (assuming you want the object at index i):
params.team[i].name_first
To create an array of first names:
params.team.map(x => x.name_first)

Json Slupper assert and extract

I'm using the next Json
{
"ID": 8,
"MenuItems": [
{
"ID": 38,
"Name": "Home",
"URL": "{\"PageLayout\":\"Home\",\"Icon\":\"home\"}",
"Culture": "en",
"Children": null
},
{
"ID": 534,
"Name": "GUIDE ",
"URL": "{''PageLayout'':''Page A'', ''Icon'':''A''}",
"MenuType": 1,
"PageID": 0,
"Culture": "en",
"Children": [
{
"ID": 6,
"Name": "Form A",
"URL": "[''Type'':''Form A'',''Icon'':''Form'',''ItemID'':\"358\"]",
"Culture": "he",
"RuleID": 0
},
{
"ID": 60,
"Name": "Drama",
"URL": "[''Type'':''Form B'',''Icon'':''Form'',''ItemID'':\"3759\"]",
"Culture": "en",
"RuleID": 0
}
]
}
]
}
i'm using Groovy script in soapUI and i need to:
Assert the exitance of node that has the name GUIDE
Extract a list of all Itemsid
You can parse the JSON content using JsonSlurper and then work with the results like so:
import groovy.json.JsonSlurper
// Assuming your JSON is stored in "jsonString"
def jsonContent = new JsonSlurper().parseText(jsonString)
// Assert node exists with name GUIDE
assert(jsonContent.MenuItems.Name.contains("GUIDE"))
// Get list of ItemIDs
def itemList = jsonContent.MenuItems.Children.URL.ItemID[0].toList()
// List the items
itemList.each {log.info it}
Note that the above will fail given your current example, because of a few issues. Firstly, Name contains "GUIDE " (trailing space) rather than "GUIDE" (so you will need to adapt accordingly). Secondly, it is invalid JSON; the URL nodes have various erroneous characters.
On a side note, if you first need to retrieve your JSON from the response associated with a previous TestStep (say one called "SendMessage") within the existing testCase, this can be done as follows:
def jsonString = context.testCase.getTestStepByName("SendMessage").testRequest.response.getContentAsString()