How to pass list of objects in json object - json

Hi I am developing small application in which I am trying to pass some data in http post method. So I want to send my data like this form
"storeid": "151",
"floordata": {
"entry": [
10,
15
],
"exit": [
10,
15
],
"section": [
{
"id": "0",
"sectionname": "ABC",
"category": "office",
"boundary": [
[
85,
258
],
[
85,
298
],
[
125,
298
],
[
125,
258
],
[
85,
258
]
"description": "Mobile based company"
}
]
},
"category": null,
"description": null
so my problem is regarding section parameter. I am doing this for section parameter.
String section = "section=";
// Problem for me is here ...
JSONArray sections = new JSONArray();
List<List<Float>> sectionCords = new ArrayList<List<Float>>();
List<Float> sectionCordData = new ArrayList<Float>();
sectionCordData.add(0.0f);
sectionCordData.add(0.1f);
List<Float> sectionCordData1 = new ArrayList<Float>();
sectionCordData1.add(0.0f);
sectionCordData1.add(0.1f);
sectionCords.add(sectionCordData);
sectionCords.add(sectionCordData1);
JSONObject sectionObj = new JSONObject();
//List<JSONObject> cordList = new ArrayList<JSONObject>();
try {
sectionObj.put("category", "office");
sectionObj.put("description", "Mobile based company");
sectionObj.put("sectionname", "mobiotics");
sectionObj.put("id", 0);
sectionObj.put("boundary", sectionCords); // Check Here i am sending as list ...
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sections.put(sectionObj);
section += sections;
section +="&";
But In actual it my section boundary parameter going as string instead of list. Like this
boundary=[
[
0.0,
0.1
],
[
0.0,
0.1
]
],storeid=156&floor=2&section=[
{
"id": 0,
"sectionname": "mobiotics",
"category": "office",
"boundary": "[[0.0, 0.1], [0.0, 0.1]]", // See here is my problem ...
"description": "Mobile based company"
}
],entry=[
10,
15
],exit=[
10,
15
]
How to send it as list instead of string. Need Help. Thank you.

Define sectionChords, and sectionCordData* as JSONArray instead of List:
JSONArray sectionChords = new JSONArray();
JSONArray sectionCordData = new JSONArray();
sectionCordData.put(0.0f);
sectionCordData.put(0.1f);
JSONArray sectionCordData1 = new JSONArray();
sectionCordData1.put(0.0f);
sectionCordData1.put(0.1f);
sectionCords.put(sectionCordData);
sectionCords.put(sectionCordData1);

It must do what you want according to docs.
Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection.
But it puts JSON representation of your object as String. So you should use either JSONArrays or Java objects. You should not mix them.

controller :
public JsonResult Index()
{
List<Location> location = (from a in db.Locations select a).ToList();
return Json(location, JsonRequestBehavior.AllowGet);
}

Related

How to fetch data from Dictionary<string, dynamic> (Json DeserializeObject)

I have Deserialized dynamic Json using Newtonsoft. The JSON is complex and dynamic.
{
"last_updated": " ",
"regions": {
"antarctica": {
"name": "Antarctica",
"totals": [],
"list": [
"aq",
"bv",
"gs",
"tf",
"hm"
]
},
"world": {
"name" : "",
"totals": {
"confirmed": 250566,
"daily_confirmed": 0,
"recovered": 202098,
"deaths": 35205,
"daily_deaths": 0,
"critical": 676,
"tests": 7249844
},
"list": [
{
"country": "Italy",
"country_code": "it",
"state": "Lombardy",
"confirmed": 85775,
"deaths": 15662,
"critical": 231,
"recovered": 231,
"tests": 43442,
"daily_confirmed": -1,
"daily_deaths": -1
}, and so on ..
To overcome the data type issue I have used the dynamic objects
[JsonTypedExtensionData]
public Dictionary<string, dynamic> items { get; set; }
Up to This works well. Now I am trying to fetch the data out of this dynamic Dictionary
var report = await GetCountryReport();
Dictionary<string, dynamic> Dict = report.regions.results["world"].items;
I'm getting data as Dict Count (2)
[0] = {[list, {[ {"country": "Italy","confirmed": 4149,"deaths": 55,"recovered": 2916,"Incidence_Rate": "54.408517127144925","Case-Fatality_Ratio": "1.274822260357931","last_updated": "2020-08-10T22:30:32Z","...
[1] = {[totals, {{"confirmed": 20218306,"recovered": 12814226,"deaths": 737481,"critical": 64743,"tests": 370260493}}]}
How do I fetch the values of each element from the Dictionary like "values.list.country" etc..?
Visual Studio debug - output
You can do it like below:
var list = Dict.Where(x => x.Key == "list").Select(x => x.Value).SingleOrDefault();
var data = ((JArray)list).Select(x => new
{
country = (string)x["country"],
state = (string)x["state"],
confirmed = (int)x["confirmed"]
//...other properties in list
}).ToList();
The data structure is like below:
Then, you can use a foreach loop to get the specify value:
foreach(var x in data)
{
var country = x.country;
var state = x.state;
var confirmed = x.confirmed;
}

How to concatenate / append a JsonObject to a JsonArray

Given the following code which gets called variously in the code, and then gets written to a file (separate method), I simple need to append the next value into the array. This is probably a simple Collections question but wasn't sure if there was a specialized Gson way of doing this:
public static void metricAsJSON(String testName, long testTime) {
Date date = new Date();
Timestamp ts = new Timestamp(date.getTime());
JSONObject obj = new JSONObject();
obj.put("testname", testName);
obj.put("Duration", testTime);
obj.put("Timestamp", ts.toString());
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(obj.toJSONString());
jsoncontent = gson.toJson(je);
JsonArray jsonArray = new JsonArray();
jsonArray.add(je);
jsoncontent = gson.toJson(jsonArray);
}
public static JsonArray appendMetricAsJson(String jsoncontent){
JsonArray jsonContentList = new JsonArray();
jsonContentList.add(jsoncontent);
return jsonContentList;
FileWriter fw1 = new FileWriter(f1, true);
PrintWriter pw1 = new PrintWriter(fw1);
if (f1.exists() && f1.isFile()) {
pw1.println(jsonContentList);
pw1.flush();
pw1.close();
fw1.close();
}
}
Current output:
[
{
"Duration": 30,
"testname": "Shopping link click to dropdown display time:",
"Timestamp": "2019-10-15 09:47:53.804"
}
]
Desired output:
[
{
"Duration": 30,
"testname": "Shopping link click to dropdown display time:",
"Timestamp": "2019-10-15 09:45:13.334"
},
{
"Duration": 16,
"testname": "Clothing link click to dropdown display time",
"Timestamp": "2019-10-15 09:44:34.356"
},
{
"Duration": 24,
"testname": "Toys link click to dropdown display time",
"Timestamp": "2019-10-15 09:46:33.453"
},
{
"Duration": 34,
"testname": "Electrics link click to dropdown display time",
"Timestamp": "2019-10-15 09:47:53.566"
}
]

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)
}

Access child token in JSON

In the below JSON I was trying to access the second array in the header.Basically "Node", "Percentage", "Time","File System" needs to captured as I will have to insert into SQL.My code is giving the complete array of header.
JObject jsonObject = JObject.Parse(jsonString);
List<string> childTokens = new List<string>();
foreach (var childToken in jsonObject.Children<JProperty>())
childTokens.Add(childToken.Name);
foreach (string childToken in childTokens)
{
if (jsonObject[childToken] is JObject)
{
JObject jObject = (JObject)jsonObject[childToken];
var jProperty = jObject.Children<JProperty>();
try
{
if (jProperty.LastOrDefault(x => x.Name == "header") != null)
{
foreach (var headerValue in jProperty.LastOrDefault(x => x.Name == "header").Value.Children())
table.Columns.Add("[" + headerValue.ToString() + "]");
table.Columns.Add("[ID]");
table.Columns.Add("[comments]");
}
JSON sample:
"DISK" : {
"alarm_count" : 5,
"column_width" : [
12,
14,
16,
14
],
"header" : [
[
"",
"Max Disk Usage",
3
],
[
"Node",
"Percentage",
"Time",
"File System"
]
] }
I can have number of arrays in header .. don't want to hardcode it.. I should be always be able to pick the last array in header child token..Please advise .. thanks
Assuming your json snippet was valid and is part of an object like:
{
"DISK": {
"alarm_count": 5,
"column_width": [
12,
14,
16,
14
],
"header": [
[
"",
"Max Disk Usage",
3
],
[
"Node",
"Percentage",
"Time",
"File System"
]
]
}
}
You could do this:
JObject obj = ...;
var secondHeader = obj["DISK"]["header"].Last();

GSON deserialize as array although JSON source is object

I'd like to deserialize this using GSON into a list of Post, but can't figure out how to tell GSON how to ignore the root element "posts" (as its an object) and just process the array.
I've got:
Type postTypeList = new TypeToken<List<Post>>(){}.getType();
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(myJSONString);
JsonObject postsRootObj = jsonElement.getAsJsonObject();
List<Post> postList = gson.fromJson(postsRootObj.get("posts"), postTypeList);
BUT.. I'd rather not have the whole JsonParser, I'd rather just pass it directly into the gson.fromJson function.. Is there a way to do this?
{ "posts":
[
{
"username": "John",
"message": "I'm back",
"time": "2010-5-6 7:00:34"
"validator":[{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
}]
}
,
{
"username": "Smith",
"message": "I've been waiting",
"time": "2010-4-6 10:30:26"
"validator":[{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
}]
}
]}
Create a wrapper class which will have List<Post> as its member
public class PostList{
private List<Post> posts;
// getter and setters for posts
}
And then use fromJson in the similar fashion
List<Post> postList = gson.fromJson(myJSONString,PostList.class);
There is a correction from above. Usage should be :
PostList postList = gson.fromJson(myJSONString,PostList.class);
Post post = postlist.get(index) //index is the index of list you want to access