Generate JSON in JAVA - java

I want generate under JSON code in Java:
{
"rowsPerPage": 10,
"page": 1,
"total": 100,
"rows": [
{
"id": 1,
"name": "name1"
},
{
"id": 2,
"name": "name2"
},
{
"id": 3,
"name": "name3"
}
]
}
I know how generate rowsPerPage, page and total, but I don't know how generate rows?
ModelMap modelMap = new ModelMap();
modelMap.put("rowsPerPage", 10);
modelMap.put("page", 1);
modelMap.put("total", 100);

Essentially, you want something like this:
ModelMap [] rowMap = new ModelMap()[3];
for (int i=0;i<3;i++)
{
ModelMap this_row=new ModelMap();
this_row.put("id",i);
this_row.put("name","name"+i);
rowMap(i)=this_row;
}
modelMap.put("rows",rowMap);
This might need to be adjusted to meet your needs, but it should at least show you how to do it.

put each row contents in a map
for(Row row :rows){
HashMap map = new HashMap();
map.put("id",row.getId());
map.put("name",row.getName());
jsonObj.append("rows", map);
}

You should use a JSON tool like Google's GSON: http://code.google.com/p/google-gson/

Related

Convert JSONArray to List<HashMap<String,Object>> in java without GSON

I have a JSONArray from net.minidev.json which I want to convert to List<HashMap<String,Object>>.
There are many answers for converting the JSONArray using Gson.
However, I cannot add Gson as a dependency to my pom.xml, so I am looking for a way to achieve it with Java-8 features.
My JSONArray is something like this: It comprises multiple hierarchies.
[
{
"data": {
"name": "idris"
},
"children": [
{
"processStandardDeduction": 69394,
"cropId": 1,
"data": null,
"expectedQuantityPerAcre": 1220,
"name": "Red Tomato 1 quality",
"id": 1003,
"autoArchivePlotDays": 59902
},
{
"processStandardDeduction": 69394,
"cropId": 1,
"autoArchivePlotDays": 59902
},
{
"processStandardDeduction": 69394,
"cropId": 1,
"autoArchivePlotDays": 59902
}
],
"name": "Red Tomato",
"id": 1002
},
{
"data": null,
"name": "Red Tomato 1 quality",
"id": 1003,
"processStandardDeduction": 69394,
"cropId": 1,
"expectedQuantityPerAcre": 1220,
"cropName": "Tomato",
"autoArchivePlotDays": 59902
},
{
"data": null,
"name": "Red Tomato 3 quality",
"id": 1001,
"processStandardDeduction": 69394,
"autoArchivePlotDays": 59902
},
{
"processStandardDeduction": 69394,
"cropId": 1,
"data": null,
"id": 1004,
"autoArchivePlotDays": 59902
}
]
I would like to achieve same structure in List>
I tried looping each element of the JSONArray by converting it to each HashMap<String,Object> and then adding it to the List<HashMap<String,Object>>.
ObjectMapper mapper = new ObjectMapper();
List<HashMap<String, Object>> cropDetailsList = new ArrayList<>();
for (Object eachCropJson : cropDetails) { //cropDetails is the JSONArray
HashMap<String, Object> eachCropMap = (HashMap<String, Object>) mapper.convertValue(eachCropJson,
HashMap.class);
cropDetailsList.add(eachCropMap);
}
return cropDetailsList;
I would like to try a better approach using Java-8 features without using a forEach.
Thanks in advance.
If you get this JSON as String then you can use ObjectMapper.readValue method
readValue(String content, TypeReference valueTypeRef)
Code
List<HashMap<String, Object>> cropDetailsList = mapper.readValue(jsonString,
new TypeReference<List<HashMap<String, Object>>>(){});
In the same way if you want to iterate JSONArray
List<HashMap<String, Object>> cropDetailsList = cropDetails.stream()
.map(eachCropJson->(HashMap<String, Object>) mapper.convertValue(eachCropJson, HashMap.class))
.collect(Collectors.toList());
Using stream this can be done
List<HashMap<String, Object>> output = cropDetails.toList().stream().map(m -> ((HashMap<String, Object>) m)).collect(Collectors.toList());

How do I remove null values from LinkedHashMap<String,Object> with nested objects having null values

My JSON Doc is structured like this and being saved in MongoDB with null values.
{
"userId": "123456",
"session": "string",
"timestamp": 0,
"product": "tracker",
"version": "13",
"flight": "A",
"activity": "search",
"action": "opportunity",
"dataDictionary": {
"datadictionary": {
"query": "roofing",
"docid": 12,
"rank": 1,
"search": {
"id": null
}
},
"id": 40
}
I have also tried to put #JsonInclude(JsonInclude.Include.NON_NULL)
My Hash map is declared like
Map<String, Object >dataDict = new LinkedHashMap<>();
dataDict.values().removeIf(Objects::isNull);
As far as I can tell this should be removing all null values regardless of level/layer in the Map.
JSON is stored like this
{
"userId": "123456",
"session": "string",
"timestamp": 0,
"product": "tracker",
"version": "13",
"flight": "A",
"activity": "search",
"action": "opportunity",
"dataDictionary": {
"datadictionary": {
"query": "roofing",
"docid": 12,
"rank": 1,
"search": {
"id": null,
"name":"test"
}
},
"id": 40
}
Should be stored like this
{
"userId": "123456",
"session": "string",
"timestamp": 0,
"product": "tracker",
"version": "13",
"flight": "A",
"activity": "search",
"action": "opportunity",
"dataDictionary": {
"datadictionary": {
"query": "roofing",
"docid": 12,
"rank": 1,
"search": {
"name":"test"
}
},
"id": 40
}
The problem is that you are removing null values from the top level Map.
This map contains internally values that are other maps. You don't remove null values from thos maps.
Try to use a recursive function to remove all null elements from inner maps.
The json:
{
"topField": null,
"innerMap": {
"innerField": null
}
}
is equivalent to the following maps in java
Map map = new LinkedHashMap();
map.put("topField", null);
Map innerMap = new LinkedHashMap();
innerMap.put("innerField", null);
map.put("innerMap", innerMap);
If you apply the code to remove null values to map:
map.values().removeIf(Objects::isNull);
results in a map that is equivalent to the following manually built map:
Map map = new LinkedHashMap();
// map.put("topField", null);
Map innerMap = new LinkedHashMap();
innerMap.put("innerField", null);
map.put("innerMap", innerMap);
because it removes null values from the map, not from innerMap.
You can remove all null elements at any level as follow:
public void removeNull(Map map) {
map.values().removeIf(Objects::isNull);
for (Object value: map.values()) {
if (value instanceof Map) {
// Apply a recursion on inner maps
removeNull((Map) value);
}
}
}
And you can remove all null items as follow:
Map map = ...
removeNull(map);
As mentioned by others, you would need to do it in a recursive manner. For example, if you have function like removeNulls:
private boolean removeNulls(final Object o) {
if (Objects.isNull(o)) {
return true;
} else if (o instanceof Map) {
((Map) o).values().removeIf(MyClass::removeNulls);
}
return false;
}
Then, you could do it like:
dataDict.values().removeIf(MyClass::removeNulls);
This is just to serve as an example.

Custom PrintFormatting for GSON

I'm having some trouble with GSON in regards to printing. GSON has two options when it comes to printing.
Pretty Printing
Compact Printing
I intend to use a modified form of Pretty Printing and even though the documentation says JsonPrintFormatter is the class which is used to modify the output format. I can't find that class in the GSON repository!
Any ideas on why this is the case or anyway I can modify the GSON printing?
Apart from that, any libraries used to modify spacing or formatting of JSON in the Java language would also be helpful.
Pretty Print:
{
"classname": "something",
"type": "object",
"version": 1,
"properties": [
{
"propertyname": "something1",
"type": "String",
"length": 255
},
{
"propertyname": "something2",
"type": "Date",
"length": 10
}
]
}
Compact Print:
{"classname":"something","type":"object","version":1,"properties":[{"propertyname":"something1","type":"String","length":255},{"propertyname":"something2","type":"Date","length":10}]}
My Print Style:
{
"classname": "something",
"type": "object",
"version": 1,
"properties": [
{"propertyname": "something1","type": "String","length": 255},
{"propertyname": "something2","type": "Date","length": 10}
]
}
Well, it's just work in progress for now, but this should do the trick for strings with only one array. Will look into to making it more stable and able to handle more complex structures.
private static String reformat(String og){
String reformattable = og;
String[] parts = reformattable.split("\\[",2);
String arrayPart = parts[1];
String arrayOnly = arrayPart.split("]",2)[0];
reformattable = arrayOnly.replaceAll("\\{\n","{");
reformattable = reformattable.replaceAll("\",\n", "\\\",");
reformattable = reformattable.replaceAll(" +"," ");
reformattable = reformattable.replaceAll("\\{ "," {");
reformattable = reformattable.replaceAll("\n }","}");
return og.replace(arrayOnly,reformattable);
}
Result should look like this (at least for my simple class):
{
"classname": "test",
"properties": [
{"propertyname": "1", "length": 1},
{"propertyname": "1", "length": 1}
]
}

JSON to Java: How to model lists of objects into generic model

I'm making a spreadSheet using SpreadJS, and I should be able to to add, delete and change the value of a key nested inside many objects. Here is how my json is formatted:
{
"version": "10.0.0",
"sheets": {
"Sheet1": {
"name": "Sheet1",
"data": {
"dataTable": {
"0": {
"0": {
"value": 129
}
}
}
},
"selections": {
"0": {
"row": 0,
"rowCount": 1,
"col": 0,
"colCount": 1
},
"length": 1
},
"theme": "Office",
"index": 0
}
}
}
The data represents, say, the value of each cell in the spreadSheet [0,0], [0,1], [1,1] ...etc. I want to parse this data into a List of generic model, for the field dataTable i would like to represent it like this: Map<Integer, Map<Integer, ValueObj>> for example in this case <0, <0, 129>> but i didn 't find how to do that and how my model would likely be.
I am new to JSON any help is appreciated! Thanks
Then to handle data, you can have a generic class like :
class CellData<T> {
T data;
}
Then read as below :
String jsonInput = "{ \"0\": { \"0\": { \"value\": 129 } } }";
ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<Integer,HashMap<Integer,CellData<Integer>>>> typeRef =
new TypeReference<HashMap<Integer, HashMap<Integer, CellData<Integer>>>>() {};
Map<Integer, Map<Integer, CellData<Integer>>> map = mapper.readValue(jsonInput, typeRef);

Extract JSON key tags recursively - Java

I was curious if there was a way to extract all key tags (including children) within a JSON object within Java?
For example, say that I have this JSON object (the first one in a single line):
{"class":{"student":[{"firstname":"dinkar","grade":"A","nickname":["dinkar","dinkar jr"],"rollno":393,"marks":85,"lastname":"kad"},{"cars":{"model":[{"content":"Ford","spec":"RS"},"Toyota","Subaru"]},"firstname":"Vaneet","nickname":"vinni","friend":"Robert","rollno":493,"lastname":"Gupta"},{"firstname":"jasvir","nickname":"jazz","Driving":99,"rollno":593,"marks":90,"lastname":"singn"}]}}
And another view of the same JSON object:
{
"class": {
"student": [{
"firstname": "dinkar",
"grade": "A",
"nickname": ["dinkar", "dinkar jr"],
"rollno": 393,
"marks": 85,
"lastname": "kad"
}, {
"cars": {
"model": [{
"content": "Ford",
"spec": "RS"
}, "Toyota", "Subaru"]
},
"firstname": "Vaneet",
"nickname": "vinni",
"friend": "Robert",
"rollno": 493,
"lastname": "Gupta",
"firstname": "jasvir",
"nickname": "jazz",
"Driving": 99,
"rollno": 593,
"marks": 90,
"lastname": "singn"
}]
}
}
I want to obtain all key tags in this object but I do not know how many key tags there are. So what I've done is to recursively go through each element and put all unique JSON key tags into a JSON Array and print it off. This works for only the first layer, but what happens if there are multiple layers that I am unsure of? Please let me know if you have any suggestions, thanks.
List < String > JSON_tags = new ArrayList < String > ();
try {
//Obtaining root node
JSONArray root = JSONO.getJSONObject("class").getJSONArray("student");
for (int i = 0; i < root.length(); i++) {
Iterator keysI = ((JSONObject) root.get(i)).keys();
//root.getJSONObject(i).
while (keysI.hasNext()) {
String key = (String) keysI.next();
if (!JSON_tags.contains(key)) {
JSON_tags.add(key);
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//prints out a unique list of JSON tags
System.out.println(Arrays.toString(JSON_tags.toArray()));

Categories