create json object from other json objects - java

I have two json objects -- not strings, please -- that I want to combine into one json object as shown below.
The two objects:
JSONObject pen = {"plastic":"blue"}
JSONObject book = {"Maya":"Bird"}
Desired result:
JSONObject bag = {"plastic":"blue","Maya":"Bird"}
Is there an elegant way to do this? I mean without extracting the values of each pen and book and then re-insert them into bag using something like
bag.put("plastic","blue");
I am using org.codehaus.jettison.json.JSONObject if that information is necessary.

Naively, it seems like you could just do something like:
Iterator it = pen.keys();
while(it.hasNext())
{
String k = it.next();
bag.put(k, pen.getJSONObject(k));
}
// bag now has the combined key,value pairs.
But it has its obvious limitations.

Related

JSON how to access entries within entries?

Consider this:
Dogs {
001{
age{
5
}
}
002{...}
...
}
I'd like to ultimately find the age of a dog, however, I do not know how many ids there are, and which is going to be the parameter.
So how exactly can I read this JSON?
I assume it would look something like this jsonObj.dogs.(desiredDog.getID()).age, yet getID would yield either an integer or a string, and I don't know if Java would understand I'm trying to conjure up a key.
I am assuming you're using org.json.simple. All you need to do is iterate over the keys of Dog objects, obtain them and then extract their age.
JSONParser parser = new JSONParser();
JSONObject rootObj = (JSONObject) parser.parse(yourJson);
for(Object key : rootObj.keySet()){
JSONObject dog = (JSONObject) object.get(key);
int age = (int) dog.get("age");
}

Get all objects on ArrayList

can some one explain me how to get all categories value from
"categories":[{"1":1,"2":"orange","3":"mango","4":"guava","5":5,"6":6}]
result my like this 1 = 1, and 2 = orange,
what must i do i am stuck in here
public RealmList<CategoryRealm> categories;
or
p.categories = new RealmList<>();
can some one explain to me what must i do in the next method i am stuck tried searching but so damn hard to learn its diferent.
Use GSON library.
Create an object that matches your structure. I'm assuming you have a structure of
{
"categories"://the rest of the stuff here
}
class MyParentObject{
#SerializeName("categories")
ArrayList<String> myList;
}
Then use GSON to create it
MyParentObject obj = (MyParentObject)getGson().fromJson(json, classType);
and your done.
If the base is just the categories string then your json is badly formatted and you may have to do a subString call to get starting index of "[" and go from there into json management.

How to deal with json string in java servlet

A variable called wrongAnswers which is an array of javascript objects is generated on the client.
It has the form
wrongAnswers = [
{"wrongAnswer": "Manzana", "wrongQuestion": "apple"},
{"wrongAnswer": "arbol", "wrongQuestion": "tree"}
]
JSON.stringify(wrongAnswers) is used and the variable is then sent to a servlet using a form.
Once it is in the servlet, i want to convert the JSON into a Java Arraylist.
I have a class Answer with 2 variables, wrongAnswer and wrongQuestion. I would like to iterate through the JSON array, and for each object, create an Answer object with the value of wrongAnswer and wrongQuestion in that JSON Object. Each time, adding the Answer object to an ArrayList so in the end, i have an ArrayList of Answers corresponding to all the values from the JSON.
At the moment, I can use request.getParameter("json") which gets me a String with the JSON data. However, i am not sure what to do with this String.
Is there a way i can easily convert a String holding JSON data into a JsonArray or JsonObject, which i can easily iterate through, getting the value of the name: value pairs in each object?
Some example code would have been nice, but there is many ways to parse and work with JSON.
One way you could try is:
JSONArray json = new JSONArray(jsonString);
ArrayList<String> array = new ArrayList<String>();
for(int index = 0; index < json.length(); index++) {
JSONObject jsonObject = json.getJSONObject(index);
String str= jsonObject.getString("wrongAnswer");
array.add(str);
}
Try using jackson for parsing the json string: https://github.com/FasterXML/jackson
For an example, look up: How to parse a JSON string to an array using Jackson

Logical solution for creating a JSON structure

I am not sure if it possible or not but I think it can be done using JSONArray.put method.
Heres my problem:
I have got two lists:
ArrayList<Students> nativeStudents;
ArrayList<transferStudents> transferStudents = nativeStudents.getTransferStudentsList();
The JSON that I generate with transferStudents list is right here: http://jsfiddle.net/QLh77/2/ using the following code:
public static JSONObject getMyJSONObject( List<?> list )
{
JSONObject json = new JSONObject();
JsonConfig config = new JsonConfig();
config.addIgnoreFieldAnnotation( MyAppJsonIgnore.class );
if( list.size() > 0 )
{
JSONArray array = JSONArray.fromObject( list, config );
json.put( "students", array );
}
else
{
//Empty Array
JSONArray array = new JSONArray();
json.put( "students",
array );
}
return json;
}
Now what I want to get is JSON data with following structure: http://jsfiddle.net/bsa3k/1/ (Notice the tempRollNumber field in both array elements).
I was thinking of doing: (The if condition here is used for a business logic)
if(transferStudents.getNewStudentDetails().getRollNumber() == nativeStudents.getNativeStudentDetails.getStudentId()){
json.put("tempRollNumber", transferStudents.getNewStudentDetails().getRollNumber());
}
but this would add tempRollNumber outsite the array elements, I want this JSON element to be part of every entry of students array.
PS: I cant edit the transferStudents class in order to add tempRollNumber field.
Since no one has come up with anything better I'll turn my comments above into an answer.
The best way to handle this is to create an object model of your data and not create the JSON output yourself. Your app server or container can handle that for you.
Though you cannot change the objects you receive in the List you can extend the object's class to add your own fields. Those fields would then appear in the JSON when you marshall it.

put method in the json object adds value to the first of the jsonobject;

Consider following piece of code:
JSONObject json = new JSONObject();
json.put("one", 1);
json.put("two", 2);
json.put("three", 3);
If i print the jsonobject it prints like this
{"three":"1","two":"2","one":"1"}
But i want like this.
{"one":"1","two":"2","three":"3"}
Please help. Thanks in advance.
The documentation at http://www.json.org/javadoc/org/json/JSONObject.html says:
A JSONObject is an unordered collection of name/value pairs.
In other words, properties of an object are accessed by name, not by position and the default serialized form does not guarantee any specific order.
Strict positioning comes only with arrays:
JSONArray json = new JSONArray();
json.put("1");
json.put("2");
json.put("3");
json.toString(); // results in ["1", "2", "3"]
The easiest workaround to solve your problem is to use the sortedKeys() method and by iterating the JSONObject key by key, produce the JSON string manually in what ever order necessary. Implementing a custom Comparator might help also.

Categories