How to concatenate / append a JsonObject to a JsonArray - json

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"
}
]

Related

How to display JSON data in DisplayActionSheet Xamarin?

I would like to know how to fetch JSON data from a URL and display it in a DisplayActionSheet? I don't want to hardcode the data.
JSON Data
[
{
"id": 284,
"name": "Complete Task"
},
{
"id": 285,
"name": "Uncomplete Task"
},
{
"id": 286,
"name": "Close Task"
}
]
So far I have something like this, but I'm not sure if I'm doing it right:
private const string TasksMenuUrl = "json-data-url-goes-here";
private ObservableCollection<TaskMenuOptions> _taskMenu;
private HttpClient _client = new HttpClient();
private async void FetchMenu()
{
var menuContent = await _client.GetStringAsync(TasksMenuUrl);
var taskMenu = JsonConvert.DeserializeObject<List<TaskMenuOptions>>(menuContent);
_taskMenu = new ObservableCollection<TaskMenuOptions>(taskMenu);
//var action = await DisplayActionSheet("Task Actions", "Cancel", null, "Complete Task", "Uncomplete Task", "Close Task");
}
Thank you.
the last argument in DisplayActionSheet is a string[]
var taskMenu = JsonConvert.DeserializeObject<List<TaskMenuOptions>>(menuContent);
var options = taskMenu.Select(t => t.Name).ToArray<string>();
var action = await DisplayActionSheet("Task Actions", "Cancel", null, options);

Getting a value from a complex JSON file (multiple objects inside an object)

I am trying to get a value from a JSON file, however it is a complex JSON file and i'm not sure how to go about it.
The value is situated inside an object, that is inside another object, which inside another object.
The values I want to retrieve from the JSON file is "value" and "unit" situated inside the object "metric". I have been able to successfully retrieve the "name" value.
The JSON file:
{
"ingredients": [
{
"name": "breakfast sausage",
"image": "breakfast-sausage-links.jpg",
"amount": {
"metric": {
"value": 226.796,
"unit": "g"
},
"us": {
"value": 8,
"unit": "ounces"
}
}
},
I will also include the method that I parse the JSON from:
private void jsonParse(){
String url = "https://api.spoonacular.com/recipes/"+ rMealId + "/ingredientWidget.json?&apiKey=da7dd16a704f4552b70a96c1e9641b08";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("ingredients");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject ingredients = jsonArray.getJSONObject(i);
String iName = ingredients.getString("name");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.e("Volley", error.toString());
}
});
requestQueue.add(request);
}
Just focusing on your json string, try this:
let ings =
{
"ingredients": [
{
"name": "breakfast sausage",
"image": "breakfast-sausage-links.jpg",
"amount": {
"metric": {
"value": 226.796,
"unit": "g"
},
"us": {
"value": 8,
"unit": "ounces"
}
}
}
]
}
let jp = require('jsonpath');
let eat = jp.query(ings, '$..metric.*');
console.log(eat);
output:
[ 226.796, 'g' ]

How to add an JsonObject in a JsonArray at some random index

I am having a JsonAarray like below:
JsonARray ProfileTabs = [{"totalItemCount":0,"label":"Updates","name":"update"},{"totalItemCount":2,"label":"Members","url":"groups\/member\/list\/129","urlParams":[],"name":"members"},{"totalItemCount":5,"label":"Photos","url":"groups\/photo\/list","urlParams":{"group_id":129},"name":"photos"}]
As in the above JsonArray I am having 3 JsonObject at index 0, 1, 2.
Now I want to add a new JsonObject in this JsonArray at index 1.
So, I have created a new JsonObject as below:
JSONObject InfoTabJsonObject = new JSONObject();
InfoTabJsonObject.put("totalItemCount", 0);
InfoTabJsonObject.put("label", "Info");
InfoTabJsonObject.put("name", "info");
mProfileTabs.put(1, InfoTabJsonObject);
And added this JsonObject to the JsonArray at index 1, but after adding this JsonObject it replaces the original 1st index's JsonObject with the new one.
How can I achieve the index should remain properly, means that new one will be added to 1st index and the other one will adjust their index.
Please help me here, thanks in advanced.
Take a look at the below code, uses org.json.simple.JSONArray and org.json.simple.JSONObject.
JSONObject jsonObj1 = new JSONObject();
jsonObj1.put("totalItemCount", 0);
jsonObj1.put("label", "Updates");
jsonObj1.put("name", "update");
JSONObject jsonObj2 = new JSONObject();
jsonObj2.put("totalItemCount", 2);
jsonObj2.put("label", "Members");
jsonObj2.put("url", "groups/member/list/129");
JSONArray temp = new JSONArray();
jsonObj2.put("urlParams", temp);
jsonObj2.put("name", "members");
JSONObject jsonObj3 = new JSONObject();
jsonObj3.put("totalItemCount", 5);
jsonObj3.put("label", "Photos");
jsonObj3.put("url", "groups/photo/list");
JSONObject temp1 = new JSONObject();
temp1.put("group_id", 129);
jsonObj3.put("urlParams", temp1);
jsonObj3.put("name", "photos");
JSONArray array=new JSONArray();
array.add(jsonObj1); //adding objects into array
array.add(jsonObj2);
array.add(jsonObj3);
try {
// Writing to a file
System.out.println("Before addition of new object into array!");
File file=new File("test1.json");
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(array.toJSONString());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject InfoTabJsonObject = new JSONObject();
InfoTabJsonObject.put("totalItemCount", 0); //adding objects into array
InfoTabJsonObject.put("label", "Info");
InfoTabJsonObject.put("name", "info");
array.add(1, InfoTabJsonObject);
System.out.println("After addition of new object into array!");
try {
// Writing to a file
File file=new File("test.json");
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(array.toJSONString());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
test1.json The orginal one before adding new object in array.
[
{
"name": "update",
"label": "Updates",
"totalItemCount": 0
},
{
"urlParams": [],
"name": "members",
"label": "Members",
"url": "groups\/member\/list\/129",
"totalItemCount": 2
},
{
"urlParams": {
"group_id": 129
},
"name": "photos",
"label": "Photos",
"url": "groups\/photo\/list",
"totalItemCount": 5
}
]
test.json The updated one after adding new object in array.
[
{
"name": "update",
"label": "Updates",
"totalItemCount": 0
},
{
"name": "info",
"label": "Info",
"totalItemCount": 0
},
{
"urlParams": [],
"name": "members",
"label": "Members",
"url": "groups\/member\/list\/129",
"totalItemCount": 2
},
{
"urlParams": {
"group_id": 129
},
"name": "photos",
"label": "Photos",
"url": "groups\/photo\/list",
"totalItemCount": 5
}
]

Merge JSON files

Does anybody know the best way to merge 2 JSON files? I am looking to move the 'awardClaimForms' from file 1 to file 2 while keeping the same 'number'. Would consider manual work if it was a few but I'm dealing with just over 1k entries. Any direction or help would be appreciated!
File 1 contains:
{
"Notices": [
{
"awardClaimForms": "form-21",
"number": "2015-031"
},
{
"awardClaimForms": "form22",
"number": "2015-030"
},
]
}
File 2 contains:
{
"Notices": [
{
"number": "2015-031",
"link": "http://www.yahoo.com",
"title": "myother sample title",
"awardClaimDueDate": "March 01, 2013",
"datePosted": "12/01/2012"
},
{
"number": "2015-030",
"link": "http://www.google.com",
"title": "my sample title",
"awardClaimDueDate": "March 01, 2013",
"datePosted": "12/01/2012"
},
]
}
Desired Outcome:
{
"Notices": [
{
"number": "2015-031",
"link": "http://www.yahoo.com",
"title": "myother sample title",
"awardClaimDueDate": "March 01, 2013",
"awardClaimForms": "form-21",
"datePosted": "12/01/2012"
},
{
"number": "2015-030",
"link": "http://www.google.com",
"title": "my sample title",
"awardClaimDueDate": "March 01, 2013",
"awardClaimForms": "form-22",
"datePosted": "12/01/2012"
},
]
}
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class JsonMerge {
public static void main(String[] args) throws IOException, JSONException {
// Read the json from the files
FileInputStream fileOne = new FileInputStream(new File("D:\\jsonOne.json"));
FileInputStream fileTwo = new FileInputStream(new File("D:\\jsonTwo.json"));
String stringOne = null, stringTwo = null;
try {
stringOne = IOUtils.toString(fileOne);
stringTwo = IOUtils.toString(fileTwo);
} finally {
fileOne.close();
fileTwo.close();
}
// Convert them into json objects
JSONObject jsonOne = new JSONObject(stringOne);
JSONObject jsonTwo = new JSONObject(stringTwo);
// Extract the arrays from the Notices Array
JSONArray jsonOneNoticesArray = jsonOne.getJSONArray("Notices");
JSONArray jsonTwoNoticesArray = jsonTwo.getJSONArray("Notices");
JSONObject mergedJsonArray = new JSONObject();
// Iterate and compare the required condition
for (int i = 0; i < jsonOneNoticesArray.length(); i++) {
for (int j = 0; j < jsonTwoNoticesArray.length(); j++) {
JSONObject mergedJson = new JSONObject();
if (jsonOneNoticesArray.getJSONObject(i).getString("number").equals(jsonTwoNoticesArray.getJSONObject(j).getString("number"))) {
mergedJson.accumulate("number", jsonOneNoticesArray.getJSONObject(i).getString("number"));
mergedJson.accumulate("link", jsonOneNoticesArray.getJSONObject(i).getString("link"));
mergedJson.accumulate("title", jsonOneNoticesArray.getJSONObject(i).getString("title"));
mergedJson.accumulate("awardClaimDueDate", jsonOneNoticesArray.getJSONObject(i).getString("awardClaimDueDate"));
mergedJson.accumulate("datePosted", jsonOneNoticesArray.getJSONObject(i).getString("datePosted"));
mergedJson.accumulate("awardClaimForms", jsonTwoNoticesArray.getJSONObject(j).getString("awardClaimForms"));
mergedJsonArray.append("Notices", mergedJson);
break;
}
}
}
System.out.println("Done merging.. " + mergedJsonArray);
}
}
Adding the below line (instead of System.out.println line) could write the output to the file
FileUtils.write(new File("D:\\mergedJson.json"), mergedJsonArray.toString());
and here is the output of the mergedJsonArray from the above code.

How to pass list of objects in json object

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