MVC For Each loop on a multi level object - json

I have the following JSON:
{
"row2": {
"Activity_log_key": 2,
"Activity_day": "2017-01-12T00:00:00",
"Effort": 8.0,
"Comment": "comment text",
"Activity": "activity text",
"Work_group": "Project",
"Work_item": "test project 1",
"Related_category": {
"Project_phase": [
["category_name", "Design"],
["category_key", 116255]
]
}
},
"row3": {
"Activity_log_key": 3,
"Activity_day": "2017-01-12T00:00:00",
"Effort": 5.5,
"Comment": "no comments",
"Activity": "activty demo text",
"Work_group": "Project",
"Work_item": "project 2",
"Related_category": {
"Project_phase": [
["category_name", "Develop"],
["category_key", 116256]
],
"Training_provider": [
["category_name", "Analysis"],
["category_key", 116254]
]
}
}
}
I convert that JSON response to an object in the controller:
Dim client As New HttpClient
Dim request = client.GetStringAsync(url & "/effort")
request.Wait()
Dim response = request.Result
Dim jsonObj As Object = New JavaScriptSerializer().Deserialize(Of Object)(response)
ViewData("response") = jsonObj
Now I try to run a For Each loop on ViewData("response") in the view but I have no results.
How can I fix that?

Related

Adding to existing JSON from excel

I want to add to this JSON file in excel using vba.
So I have this JSON file
{
"root": [{
"STATUS_RESPONSE": {
"STATUS": {
"STATUS": {
"OWNER": "root"
}
},
"REQ_ID": "00000",
"RESULT": [{
"USER": {
"BUSINESS_ID": "A",
"USER_NUMBER": "45",
"LANGUAGE": "F"
}
},
{
"USER_SESSION": {
"USER_ID": "0000001009",
"HELP_URL": "http://google.com"
}
},
{
"USER_ACCESS": {
"SERVICES_ROLE": "true",
"JOURNALLING": "true"
}
}]
}
}]
}
I want to add another "USER" right below it so it looks like
{
"root": [{
"STATUS_RESPONSE": {
"STATUS": {
"STATUS": {
"OWNER": "root"
}
},
"REQ_ID": "00000",
"RESULT": [{
"USER": {
"BUSINESS_ID": "A",
"USER_NUMBER": "45",
"LANGUAGE": "F"
}
},
{
"USER": {
"BUSINESS_ID": "B",
"USER_NUMBER": "55",
"LANGUAGE": "E"
}
},
{
"USER_SESSION": {
"USER_ID": "0000001009",
"HELP_URL": "http://google.com"
}
},
{
"USER_ACCESS": {
"SERVICES_ROLE": "true",
"JOURNALLING": "true"
}
}]
}
}]
}
This is what I have currently
Private Sub CommandButton3_Click()
Dim z As Integer, items As New Collection, myitem As New Dictionary
Dim rng As Range
Dim cell As Variant
Dim FSO As New FileSystemObject
Dim JsonTS As TextStream
Set JsonTS = FSO.OpenTextFile("test.json", ForReading)
JsonText = JsonTS.ReadAll
JsonTS.Close
Set JSON = ParseJson(JsonText)
Set rng = Range("A5")
z = 0
For Each cell In rng
myitem("BUSINESS_ID") = cell.Offset(0, 1).Value
myitem("USER_NUMBER") = cell.Offset(0, 2).Value
myitem("LANGUAGE") = cell.Offset(0, 3).Value
items.Add myitem
Set myitem = Nothing
z = z + 1
Next
myfile = Application.ActiveWorkbook.Path & "\test.json"
Open myfile For Output As #1
Print #1, ConvertToJson(myitem, Whitespace:=2)
MsgBox ("Exported to JSON file")
Close #1
End Sub
All this does is add it below the existing JSON and is not connected to it all.
How would I go about add another "USER" right below the current one with the information from excel

Dynamically Parsing JSON with Groovy

I have a JSON document pulled back from a support system API. With my code, I want to pull out the pre-configured fields dynamically, presuming that the JSON may have more or fewer of the desired fields when my program calls the API.
I have some code that works, though it seems very convoluted and inefficient.
Here is a snippet of the pieces of JSON that I'm interested in:
{
"rows": [
{
"assignee_id": 1,
"created": "2017-01-25T14:13:19Z",
"custom_fields": [],
"fields": [],
"group_id": 2468,
"priority": "Low",
"requester_id": 2,
"status": "Open",
"subject": "Support request",
"ticket": {
"description": "Ticket descritpion",
"id": 1000,
"last_comment": {
"author_id": 2,
"body": "Arbitrary text",
"created_at": "2017-02-09T14:21:38Z",
"public": false
},
"priority": "low",
"status": "open",
"subject": "Support request",
"type": "incident",
"url": "Arbitrary URL"
},
"updated": "2017-02-09T14:21:38Z",
"updated_by_type": "Agent"
},
{
"assignee_id": 1,
"created": "2017-02-09T14:00:18Z",
"custom_fields": [],
"fields": [],
"group_id": 3579,
"priority": "Normal",
"requester_id": 15,
"status": "Open",
"subject": "Change request",
"ticket": {
"description": "I want to change this...",
"id": 1001,
"last_comment": {
"author_id": 20,
"body": "I want to change the CSS on my website",
"created_at": "2017-02-09T14:12:12Z",
"public": true
},
"priority": "normal",
"status": "open",
"subject": "Change request",
"type": "incident",
"url": "Arbitrary URL"
},
"updated": "2017-02-09T14:12:12Z",
"updated_by_type": "Agent"
}
]
}
I have an ArrayList called wantedFields that I build up from a config to define which information I want to pull out from the JSON:
["id","subject","requester_id","status","priority","updated","url"]
The complexity is that data is replicated in the API, and I only want to pull out data once, with a preference for the data in "rows" where applicable. My method for doing this is below. It feels like I'm repeating code but I can't really see how to make this work more efficiently. The JSON is held as "viewAsJson".
def ArrayList<Map<String,Object>> assignConfiguredFields(viewAsJson, wantedFields) {
//Pull out configured fields from JSON and store as Map to write as CSV later
ArrayList<Map<String,Object>> listOfDataToWrite = new ArrayList<Map<String,Object>>()
ArrayList<String> rowKeyList = new ArrayList<String>()
def validationRow = viewAsJson.rows.get(0)
//Compare one row object to config first
validationRow.each { k, v ->
if (wantedFields.contains(k)) {
wantedFields.remove(k)
rowKeyList.add(k)
}
}
ArrayList<String> ticketKeyList = new ArrayList<String>()
def validationTicket = viewAsJson.rows.ticket.get(0)
//Compare one ticket object to config first
validationTicket.each { k, v ->
if (wantedFields.contains(k)) {
wantedFields.remove(k)
ticketKeyList.add(k)
}
}
def rows = viewAsJson.rows
def tickets = viewAsJson.rows.ticket
//Pull matching ticket objects from JSON and store in Map
ArrayList<Map<String,Object>> tickList= new ArrayList<>()
ArrayList<Map<String,Object>> rowList= new ArrayList<>()
rows.each { row ->
Map<String,Object> rowMap = new HashMap<>()
row.each { k, v ->
if(rowKeyList.contains(k))
rowMap.put(k,v)
}
rowList.add(rowMap)
}
tickets.each { ticket ->
Map<String,Object> ticketMap = new HashMap<>()
ticket.each { k, v ->
if(ticketKeyList.contains(k))
ticketMap.put(k, v)
}
tickList.add(ticketMap)
}
for (int i = 0; i < rowList.size(); i++) {
HashMap<String,Object> dataMap = new HashMap<>()
dataMap.putAll(rowList.get(i))
dataMap.putAll(tickList.get(i))
listOfDataToWrite.add(dataMap)
}
println listOfDataToWrite
return listOfDataToWrite
}
I know there should be some validation for if the wantedFields ArrayList is still populated. I've iterated on this code so many times I just forgot to re-add that this time.
I don't know if you still need this code but why not try something like this.
Have a translation map and run each row through it.
Object tranverseMapForValue(Map source, String keysToTranverse, Integer location = 0){
List keysToTranverseList = keysToTranverse.split(/\./)
tranverseMapForValue(source, keysToTranverseList, location)
}
Object tranverseMapForValue(Map source, List keysToTranverse, Integer location = 0){
if(source.isEmpty() || keysToTranverse.isEmpty()){
return null
}
String key = keysToTranverse[location]
if(source[key] instanceof Map){
return tranverseMapForValue(source[key], keysToTranverse, location + 1)
}
else{
return source[key]
}
}
Map translation = [
"ticket.id": "id",
"ticket.subject": "subject",
"requester_id": "requester_id",
"ticket.status": "status",
"priority": "priority",
"updated": "updated",
"ticket.url": "url"
]
List rows = []
json.rows.each{ row ->
Map mapForRow = [:]
translation.each{ sourceKey, newKey ->
mapForRow << [(newKey): tranverseMapForValue(row, sourceKey)]
}
rows.add(mapForRow)
}

how to print json array in jsonobject when we will get element of jsonarrray at runtime

ArrayList al = new ArrayList();
//al[0] and al[1] are the json objects.
def json = new JsonBuilder()
json {
type "rel12"
total k
xyz ""
shows al[0],al[1]
emails ""
}
println json.toPrettyString()
i dont want to do the the hardcoding like al[0]. al[1].
but i need the output like
{
"type": "rel12",
"total": 2,
"xyz": "",
"shows": [
{
"extension": "zip",
"updateTime": 1477521104511
},
{
"extension": "zip",
"updateTime": 1477521104623
}
],
"emails": ""
}

Read Json array vb.net

I'm getting mad about this.
I'm very new to Json.
I need to read the array ("items") from the json example provided.
I can read all other objets like "id","title","description"...but not the array of items.
Using Newtonsoft.Jason
Code (vb.net) : >>
Dim json As String = File.ReadAllText("C:\Test\Json\test.json")
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
For Each item As JProperty In data
item.CreateReader()
Select item.Name
Case "results"
For Each comment As JObject In item.Values
txtConsole.Text = comment
Console.WriteLine(comment("id"))
Console.WriteLine(comment("title"))
Console.WriteLine(comment("description"))
Console.WriteLine(comment("tipe"))
Console.WriteLine(comment("author")("description"))
Console.WriteLine(comment("details")("conditions"))
'for each item in array
'Read the array of "products": here
'Console.WriteLine(comment("name")
'Console.WriteLine(comment("codeBar")
'next
Console.WriteLine(comment("details")("benefits"))
Console.WriteLine(comment("details")("price"))
Console.WriteLine(comment("details")("discount"))
Console.WriteLine(comment("details")("pays"))
Console.WriteLine(comment("datefrom"))
Console.WriteLine(comment("dateto"))
Next
End Select
Next
Json file >>
{
"total": 1,
"results": [
{
"id": 208,
"title": "This is the title",
"description": "This is the descripcion",
"tipe": "This is type",
"author": {
"descripcion": "description of author"
},
"details": {
"conditions": {
"items": [
{
"quantity": 6,
"products": [
{
"name": "Product one",
"codeBar": "7891000100103"
},
{
"name": "Product two",
"codeBar": "7894900061604"
},
{
"name": "Product three",
"codeBar": "7894900010015"
},
{
"name": "Product four",
"codeBar": "7894900092011"
}
]
}
]
},
"benefits": null,
"price": null,
"discount": null,
"pays": 5
},
"datefrom": "2015-08-06T00:00:00.000-0300",
"dateto": "2016-12-31T23:59:59.000-0200"
}
]
}
Desire Console output >>
208
This is the title
This is the descripcion
This is type
items
quantity: 6
products
"name": "Product one",
"codeBar": "7891000100103"
"name": "Product two",
"codeBar": "7894900061604"
"name": "Product three",
"codeBar": "7894900010015"
"name": "Product four",
"codeBar": "7894900092011"
5
06/08/2015 00:00:00
31/12/2016 22:59:59
Please, help me...thank u very much in advance !!
This might point you in the right direction. I was able to access the products array this way:
' Open the file using a stream reader.
Dim sr As New StreamReader(System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\json.txt")
Dim line As String
line = sr.ReadToEnd()
line = "[" & line & "]"
Dim jArray__1 = JArray.Parse(line)
For Each item In jArray__1.SelectToken("[0].results.[0].details.conditions.items.[0].products")
MessageBox.Show(item.ToString)
Next
Thak you very much guys !!
I finally did it like this...
For Each element In comment.SelectToken("details")("conditions")("items")(0)("products")
Console.WriteLine(element("name"))
Console.WriteLine(element("codeBar"))
Next

VB.NET need help in deserialization of a JSON

Hey I need help in deserializing this:
{
"success": true,
"rgInventory": {
"2722309060": {
"id": "2722309060",
"classid": "939801430",
"instanceid": "188530139",
"amount": "1",
"pos": 1
},
"2722173409": {
"id": "2722173409",
"classid": "937254203",
"instanceid": "188530139",
"amount": "1",
"pos": 2
},
"2721759518": {
"id": "2721759518",
"classid": "720293857",
"instanceid": "188530139",
"amount": "1",
"pos": 3
},
"2721748390": {
"id": "2721748390",
"classid": "310777652",
"instanceid": "480085569",
"amount": "1",
"pos": 4
}
}
}
at the end it should look like:
2722309060#2722173409#2721759518#2721748390
Dim result = JsonConvert.DeserializeObject(jsonstring) 'deserialize it
Dim tempfo As String = result("rgInventory").ToString 'get rgInventory
Console.WriteLine(tempfo)
how i can deserialize all 'id's?
The json contains a Dictionary of items, the IDs you want are the keys. If you deserialized it, you could get them from the Dictionary. Otherwise, you can use JParse and linq to get them:
Dim jstr As String = ...
' parse the json
Dim js As JObject = JObject.Parse(jstr)
' extract the inventory items
Dim ji As JObject = JObject.Parse(js("rgInventory").ToString)
' get and store the keys
Dim theIds As List(Of String) = ji.Properties.Select(Function(k) k.Name).ToList()
I suspect that when "success" is false that the resulting items list will be empty. Test that it works:
For Each s As String In theIds
Console.WriteLine(s)
Next
Result:
2722309060
2722173409
2721759518
2721748390