GSON to JSON - multiple objects - java

I am using GSON and would like to have it convert multiple lists to JSON - that will be one object - is there any way to do this without manipulating the lists or using a new data structure?
List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
list1.populate();
list2.populate();
Gson gson = new GsonBuilder().create();
gson.toJson(list1, list2);// ----> THIS IS WHAT I WANT
I want the result to be something like this - pseudocode JSON
first result of first list to correlate with first result of second list
{
list1[element1]: list2[element1],
list1[element2]: list2[element2],
list1[element3]: list2[element3].....
}

What's wrong with modification of the list in memory?
list1.populate();
list2.populate();
list1.addAll(list2);
Gson gson = new GsonBuilder().create();
gson.toJson(list1);
Obviously populate isn't a method of lists, but you can only convert single objects to JSON
If order is at all important, you have to find a way to populate a singular list containing the data in the order you need

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

JSON Object Containing Array To ArrayList<POJO> With GSON

I am new to JSON and GSON, and I am taking a JSON feed from an input stream, and put it into an array list of custom objects. The JSON feed contains a single object, which contains an array of more objects. It looks something like this:
{ "container":[
{"item_1":"item one"},
{"item_2":"item two"},
{"item_3":"item three"}
]}
I am currently using a TypeToken with a Map to obtain the container object along with the list of objects as an array list of custom objects. Like so:
InputStreamReader input = new InputStreamReader(connection.getInputStream());
Type listType = new TypeToken<Map<String, ArrayList<Item>>>(){}.getType();
Gson gson = new GsonBuilder().create();
Map<String, ArrayList<Item>> treeMap = gson.fromJson(input, listType);
ArrayList<Item> objects = treeMap.get("container");
input.close();
I would like to know if there is a way to skip the step of creating a Map<String, ArrayList<Item>>, and go directly from the input stream to an ArrayList<Item> using GSON. Just to consolidate my code, creating a map seems like an unnecessary step.
One option is to define a wrapper type which has a container property, and then deserialize the JSON to that type instead of to a Map.
public static class Wrapper {
public List<Item> container;
}
Wrapper wrapper = gson.fromJson(input, Wrapper.class);
List<Item> objects = wrapper.container;

search text for strings in between strings android

i have this really long JSON text where i have to locate a string of a movie title that is between following:
((((((( .","title":" AND ","type":" )))))))
i have read on other solutions like :
String mydata = json;
Pattern pattern = Pattern.compile(".\",\"title\":\"(.*?)\",\"type\":\"");
Matcher matcher = pattern.matcher(mydata);
while (matcher.find())
{
testare += (matcher.group(1));
}
and also the way messier:
List<String> strings = Arrays.asList( json.replaceAll("^.*?.\",\"title\":\"", >>"")
.split("\",\"type\":\".*?(.\",\"title\":\"|$)"));
ArrayAdapter<String> myAdapter = new
ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, strings);
final ListView myList = (ListView) findViewById(R.id.listVyn);
myList.setAdapter(myAdapter);
Json contains the entire text in the JSON as a string.
My problem is that when i search for Dirty it recommends movies that contains "Dirty" and i want to search the string and pick out all the titles. But for some reason it seems to loop the first movie name, which is "Dirty" and then ignore the rest. what should i do about this?
If I'm understanding you correctly, I might suggest a different approach. If you deserialize the json object to a java object, you'll should find the problem much easier. I.e., instead of working with json, you'd be working with a java object, containing the information from the json. You can do this in a number of ways, for instance using Gson:
Gson gson = new Gson();
MyObject myObject = gson.fromJson(jsonString, MyObject.class);
Once you've done this, you can use myObject to get text from the object. E.g., myObject.getTitle(). If you then want to use regex on that string, that's all good. But I wouldn't use regex on the json.
In order to create MyObject.class, which represents the json, you can use:
http://pojo.sodhanalibrary.com

Get element name with GSON

I have JSON like this:
{"foos":[{"id":1}, {"id":2}]}
I can turn it into List<Foo> pretty simply with GSON, like this:
Type t = new TypeToken<List<Foo>>(){}.getType();
JsonObject resp = new Gson().fromJson(
new JsonParser().parse(json).getAsJsonObject().get("foos",t);
But let's assume that I also have another JSON, where the name of the array and type changes
{"bars":[{"id":3},{"id":9}]}
Of course I could just swap the "foos" parameter for "bars", but if it's possible, I'd like my software to do it for me.
Is there a way to extract the name of the array child with the GSON library?
I'm not sure if I understood what you want correctly, but aren't you referring to the use of generics? I mean you could write a method that returns you a List of your relevant class? Something along the lines of
Type type = new TypeToken<List<MyClass>>() {}.getType();
List<MyClass> myObjects = getMyObjects(new JsonParser().parse(json).getAsJsonObject().get("foos"), type);
public static List<T> getMyObjects(String jsonString, Type type) {
Gson gson = new Gson();
List<T> myList = gson.fromJson(jsonString, type);
return myList;
}
Looking at your JSON examples, I assume that the name of the list element can change, but not the content of the list. If this is correct, you could parse your JSON response just like this:
Type mapType = new TypeToken<Map<String, List<Foo>>>() {}.getType();
Map<String, List<Foo>> map = gson.fromJson(jsonString, mapType);
And then you can access the name of the list with:
String listName = map.keySet().iterator().next();
If the content of the list could also change, things get a bit more complicated...

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