Get all objects on ArrayList - java

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.

Related

How can i add additional field to each object in array node using jackson java?

i have list of masters that have two fields that are name and rating and after serialization to array node i need to add one more field to each object
for example i have json
[{"masterName":"Bruce","rating":30},{"masterName":"Tom","rating":25}]
and i have list of servisec in json format that look like that
[{"masterName":"Bruce","services":["hair coloring","massage"]},{"masterName":"Tom","services":["hair coloring","haircut"]}]
i need it to looks something like that
[{"masterName":"Bruce","rating":30,"services":"hair coloring,massage"},{"masterName":"Tom","rating":25,"services":"hair coloring, haircut"}]
How can do it by using jackson?
I would approach it this way. Since you want to use Jackson.
First of all, I would extend the Master class by adding the services (which seems to be an array with Strings).
So the class would look something like this:
public class Master
{
private String masterName;
private int rating;
private List<String> services = new ArrayList<>(); // THE NEW PART
// Whatever you have else in your class
}
Then you could get your JSON array, I am supposing that it comes as a String for simplicity. Serialize this array in an array with Master objects and then you can add the services as said above.
e.g.
String yourJsonString = "[{\"masterName\":\"Bruce\",\"rating\":30},{\"masterName\":\"Tom\",\"rating\":25}]";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
List<Master> theListOfMasters = new ArrayList<>();
// Read them and put them in an Array
Master[] mastersPlainArr = mapper.readValue(yourJsonString, Master[].class);
theListOfMasters = new ArrayList(Arrays.asList(mastersPlainArr));
// then you can get your masters and edit them..
theListOfMasters.get(0).getServices.add("A NEW SERVICE...");
// And so on...
// Then you can turn them in a JSON array again:
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(theListOfMasters);

Parsing a JSON document

actually I'm struggeling with parsing the following JSON doc: LINK
I have a class which is saving the content in a String (rawData). After that I want to parse it with Gson.
DownloadedCategories dcats = new Gson().fromJson(rawData, DownloadedCategories.class);
My goal is to have a List of an extra datatype of the 21 main categories, and in the extra datatype saved in another List the subcategories.
My approach was to create the new datatype mainCategory which includes the List of the subcategories.
The problem is that i can't do the DownloadedCategories class like this:
public class DownloadedCategories
{
private List<mainCategories> categories;
public List<mainCategories> getCategories;
{
return categories;
}
}
Has someone an idea how to fix my issue?
Looks like that Json from your link is not formatted to fit in your object.
You need to know in which attribute you will put your categories since you are trying to parse a Json array in an object. In your DownloadedCategories the attribute is categories. So you need to wrap your Json in an attribute categories.
String wellFolrmedJson = "{\"categories\": " + rawData + "}";
DownloadedCategories dcats = new Gson().fromJson(wellFolrmedJson , DownloadedCategories.class);
Gson will bind the json array in your Object list.
The best way to parse your data is by using array as starting point like in this example.
mainCategories[] dcats = new Gson().fromJson(rawData , mainCategories[].class);

JSON construction

I am new to JSON and getting confused everytime I create a new one.
I am trying to create a JSON array like this :
{
"id":"2003",
"HouseMD" :
{
"Doctor_1": "Thirteen",
"Doctor_2" : "Chase"
"Doctor_n" : "Someone"
}
}
Basically I am trying to add info dynamically from Doctor_1 to Doctor_n" in a for loop. and if I use a JSON Object I am only getting the last value when I finally print it.
How do I get something that I want?
Any help appreciated.
Thanks.
JSON arrays look like this:
{ "id":"2003", "HouseMD" : [{ "Doctor_1": "Thirteen"}, {"Doctor_2" : "Chase"}, {"Doctor_n" : "Someone" }]}
Notice the square bracket that surrounds each JSON object in the array.
Here is the link to the JSON website, which can offer more info:
JSON
Note that in order for the code below to work, you will also need the JSON library, which you can easily download from here Download Java JSON Library
I don't know the approach you are using, but based on the format you want, I would do something like this:
JSONObject data = new JSONObject();
data.put("id", "2003");
JSONObject doctors = new JSONObject();
//here I suppose you have all doctors in a list named doctorList
//and also suppose that you get the name of a doctor by the getName() method
for (int i = 0; i < doctorList.size(); ++i)
{
doctors.put("Doctor_" + (i+1), doctorList.get(i).getName();
}
data.put("HouseMD", doctors);
//then you could write to a file, or on screen just for test
System.out.println(data.toString());
However, I feel you need to become more comfortable with JSON, so try starting here.

create json object from other json objects

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.

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.

Categories