I am creating JSON object and send over the network , like
org.codehaus.jettison.json.JSONObject json = new org.codehaus.jettison.json.JSONObject();
json.put("id", "15");
json.put("code", "secret");
json.put("type", "new type");
Also I have links of photos what I want to put into this JSON
my links like http://box.com/images/photo.jpg,http://box.com/images/photo1.jpg
http://box.com/images/photo2.jpg, http://box.com/images/photo3.jpg
As I understand I must have some list/array and put like
json.put("images", links)
How to do it, put and parse... I need one key, and list of values.
Is JSON array is useful for this?
Thanks
Yes. JSONArray is what you need.
List <String> links = getLinks();
JSONArray array = new JSONArray();
for (String link : links)
array.put(link);
JSONObject obj = new JSONObject();
//put id, code, type...
obj.put("images", array);
Check out the JSONArray class.
http://jettison.codehaus.org/apidocs/org/codehaus/jettison/json/JSONArray.html
You'll create a JSONArray and use that in your put command.
Related
I want to create an Application that can auto-create Memes. Every Meme from the API has different amounts of boxes (fields where the text can sit). Now I want to create an HTTP Request to get the fields for a specific meme ID.
The HTTP Request is working fine but I don't know how to deserialize and filter the received string.
Here is the JSON I want to Deserialize with GSON:
https://api.imgflip.com/get_memes
The solution is:
You need to get a JsonObject then in a JsonElement deserialize the "top-level-elements" and get it as a JsonArray. Then you can Loop through the array and get what you need.
JsonObject jsonObject = new Gson().fromJson(content.toString(), JsonObject.class);
JsonElement entry = jsonObject.getAsJsonObject("data").getAsJsonArray("memes");
JsonArray entryArray = entry.getAsJsonArray();
for (JsonElement element : entryArray) {
JsonObject jsonObjectLoop = element.getAsJsonObject();
if(jsonObjectLoop.get("id").getAsString().equals("14371066")) {
System.out.println(jsonObjectLoop.get("box_count").getAsString());
}
}
I have a large file with many JSON objects similiar to the following. I need to parse everything to get the "bought_together" items as an array using the org.json library. I'm having trouble accessing anything nested in "related".
What is the required code to retrieve "bought_together" as a list?
{
"asin": "11158732",
"title": "Girls Ballet Tutu Zebra Hot Pink",
"price": 3.17,
"imUrl": "http://ecx.images-amazon.com/images/I/51fAmVkTbyL._SY300_.jpg",
"related":
{
"also_bought": ["L00JHONN1S", "B002BZX8Z6"],
"also_viewed": ["F002BZX8Z6", "B00JHONN1S", "B008F0SU0Y", "B00D23MC6W", "B00AFDOPDA"],
"bought_together": ["D202BZX8Z6"]
},
"salesRank": {"Toys & Games": 211836},
"brand": "Coxlures",
"categories": [["Sports & Outdoors", "Other Sports", "Dance"]]
}
Here is my attempt (Please note, this is within a MapReduce program so some lines may seem out of context.):
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONArray boughtTogether = new JSONArray(object.getJSONArray("bought_together"));
using the following code, I hope it's help you.
//this will be your json object that contains and convert your string to jsonobject
//if you have json object already skip this.
JSONObject yourJSON = new JSONObject(targetString);
//getting the "related" jsonObject
JSONObject related = yourJSON.getJSONObject("related");
//getting the "bought_together" as an jsonArray and do what you want with it.
//you can act with jsonarray like an array
JSONArray bought_together = related.getJSONArray("bought_together");
//now if you run blow code
System.out.print(bought_together.getString(0));
//output is : D202BZX8Z6
-------update according to update the question------
you should change your code like this:
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONObject related = object.getJSONObject("related");
JSONArray boughtTogether = related.getJSONArray("bought_together");
-------update-------
i think you need to this point (it's not technicality all of they difference)
every thing are in {} , they will be JSONObject and the relation
is key and value like :
{"name":"ali"}
this is a jsonobject and the value of key "name" is ali and we call it
like:
myJsonObject.getString("name");
every thing are in [] ,they will be JSONArray and the relation is
index and value like :
["ali"]
this is a JsonArray the value of index 0 is ali and we call it
like:
myJsonArray.getString(0);
so in your case:
your total object is a JSONObject
the value of "related" key is still a JSONObject
the value of "bought_together" key (which is inside the value of {jsonobject} "related" key) is a JSONArray
My JSON Data looks something like this:
[
"{\"pid\":\"1\",\"title\":\"New CEO announced\",\"titleirish\":\"CEO nua\",\"content\":\"Bernard Byrne has been announced as the new CEO. Rejoice!\",\"contentirish\":\"Is Bernard Byrne an CEO. B\\\\u00edg\\\\u00ed s\\\\u00e1sta!\",\"imageurl\":\"http:\\\\\\/\\\\\\/scoiluiriada.ie\\\\\\/wp-content\\\\\\/uploads\\\\\\/2014\\\\\\/02\\\\\\/IMG_1781-150x112.jpg\",\"category\":\"News\",\"publishedby\":\"Andy\",\"modified\":\"2015-07-01 16:21:13\",\"buildings\":\"Bankcentre,Hume House,Time House\"}",
"{\"pid\":\"2\",\"title\":\"New CTO pronounced\",\"titleirish\":\"CEO nua\",\"content\":\"Bernard Byrne has been announced as the new CEO. Rejoice!\",\"contentirish\":\"Is Bernard Byrne an CEO. B\\\\u00edg\\\\u00ed s\\\\u00e1sta!\",\"imageurl\":\"http:\\\\\\/\\\\\\/scoiluiriada.ie\\\\\\/wp-content\\\\\\/uploads\\\\\\/2014\\\\\\/02\\\\\\/IMG_1781-150x112.jpg\",\"category\":\"News\",\"publishedby\":\"Andy\",\"modified\":\"2015-07-02 10:09:10\",\"buildings\":\"Hume House\"}",
....
So far I have the following code:
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(allData); // allData = JSON String above
JSONArray nitems = (JSONArray)obj;
This gives me an array of all the objects I want to parse. (it works perfectly)
Now, looping through this array, I would like to get the object member values.
Something like this:
nitems.get(0).getValueOf("title") // should return "New CEO announced"
nitems.get(0).getValueOf("titleirish") // "CEO Nua" etc.
This obviously doesn't work, what code do I use instead.
Thanks for any answers in advance.
Fixed with help from some comments. Here is solution:
JSONObject obj2 = (JSONObject)new JSONParser().parse(nitems.get(i).toString());
System.out.println(obj2.get("title").toString());
This is a basic Java question I think that I can't work out how to get around.
I get data from Google Analytics API and store the rows in my database as a string as a JSONArray
[["New Zealand","Auckland","1640","8.795731707317072","516.4469512195122"],["New Zealand","Wellington","1314","8.428462709284627","580.3302891933029"]]
For Google Maps I need a JSON Array:
function drawMap() {
var data = google.visualization.arrayToDataTable([
['City', 'Popularity'],
['New York', 200],
['Boston', 300],
['Miami', 400],
['Chicago', 500],
['Los Angeles', 600],
['Houston', 700]
]);
From https://developers.google.com/chart/interactive/docs/gallery/geomap
I need to change my data, by parsing it and iterating through it to remove the first (i.e. "New Zealand") and last variable from each object - I also need to add the headers i.e. ['City', 'Popularity']
Using GSonBuilder I can create JSON
[{"city":"Wellington","sessions":"1314","viewsPerSessions":"8.428462709284627","avgDuration":"8.428462709284627"},{"city":"Christchurch","sessions":"432","viewsPerSessions":"10.127314814814815","avgDuration":"10.127314814814815"}]
How do I turn that into a JSON Array?
I use the JSON parse of Android. With this you can get what you want.
Try this:
JSONArray js_data = [["New Zealand","Auckland","1640","8.795731707317072","516.4469512195122"],["New Zealand","Wellington","1314","8.428462709284627","580.3302891933029"]];
int lenght = js_data.length();
JSONArray city;
for(int i=0;i<length;i++) {
//get each city
city = js_data.getJSONArray(i);
String nameCity = city.getString(0);
String pop = city.getString(4);
//Create a object JSON or whatever you want with this data
JSONArray js_array = new JSONArray();
js_array.put(city); js_array.put(pop);
//And put on a list
js_map.put(js_array);
}
This is a basic java coding.
Hope it's helps.
I have searched the web for answer and everywhere is done like this:
JSONObject params = new JSONObject();
Gson gson = new Gson();
params.put("Event", gson.toJson(myEvent));
But this is returning me Json like this with all escapings on ":
"Event":"{\"Test1\":\"TestValue1\",\"TestObj\":{\"Test2\":\"TestValue2\",\"Test3\":\"TestValue3\"...
How can I have Json free of all escapings, just like this:
"Event":"{"Test1":"testValue1","TestObj":{"Test2":"testValue2","Test3":"testValue3"...
Cheers mates.
I can pass the object like this, property by property:
createEvent.put("Test1", myObj1.Test1);
createEvent.put("Test2", myObj2.Test2);
and pass the Json to api, but Notes is with escapings:
String myNoteListJson = new Gson().toJson(myNoteList);
createEvent.put("Notes", myNoteListJson);
I found an answer, here it is:
I am passing property by property:
createEvent.put("Test1", myObj1.Test1);
createEvent.put("Test2", myObj2.Test2);
and the Notelist problem is solved like this:
JSONArray mJSONArray = new JSONArray(myNoteList);
createEvent.put("Notes", mJSONArray);