I have a json array in database. I want to get only value ignoring the key and send it to ajax call.
Json string I have while saving:
{
"cells":
[
{
"type": "devs.TooledModel",
"position":
{
"x": 200,
"y": 100
},
"size":
{
"width": 71,
"height": 100
},
".":
{
"magnet": false
}
}
]
}
I want to return the exact json array from database but I am getting a key appended because I am using a map in java servlet to retrieve json:
List<Map<String, Object>> result = new ArrayList<>();
while (rSet.next()) {
Map<String, Object> row = new HashMap<>();
row.put("JSON_Diagram", rSet.getString("JSON_INFO"));
result.add(row);
}
json received: JSON_Diagram: "cells%5B0%5D%5Btype%5D=devs.TooledModel&cells..
How do I remove the key JSON_Diagram and get only value ? Tried with Object value = result.get(0); but didn't work
You need to get a list of all the keys, loop over them and add them to your map and if you need only value add values only to list as shown in the example below:
Map<String,Object> row = new HashMap<String,Object>();
Iterator iter = rSet.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = rSet.getString(key);
row.put(key,value);
result.add(value);
}
So once you have the map just do a a map.values.
[http://docs.oracle.com/javase/7/docs/api/java/util/Map.html#values()][1]
Then just use the resultant collection!
Related
I have a data that looks like so:
{
"name":{
"first": "<firstName>",
"last": "<lastName>"
},
"info": "<info>",
"place":{
"location": "<location>",
},
"test": "<test>"
}
However, I want to customize the Response json and group the data by the location.
In other words I would like to have a response like this:
"location":[{
"name": <location>,
user: [{
"name": <firstName> + <lastName>,
"info": <info>,
"test": <test>
}]
}]
I have tried to the it into a map like so:
List<Data> data= newArrayList(repository.findAll(Sort.by(Sort.Direction.ASC, "location")));
Map<String, Object> result= new HashMap<>();
for (Data d : data) {
result.put("name", d.getLocation());
result.put("user", d.getFirstName());
...
and so on, but this does not work. What is the best approach to achieve my desired result?
As of now you have a single result map, which you are then overwriting in the loop, so it will contain data for a location only, the last one. What you probably wanted to do is creating a list of those maps, which requires creating a new map inside the loop, and collecting them in a list:
List<Map<String, Object>> result=new ArrayList<>();
for(Data d : data) {
Map<String, Object> item = new HashMap<>();
item.put("name", d.getLocation());
item.put("user", d.getFirstName());
...
result.add(item);
}
Suppose I have a list of Map such as:
(Using json format just for demonstration)
List<Map> myList = [
{
"id": 12,
"name": "Harie"
},
{
"id": "Forty",
"location": "Earth"
},
{
"name": "Potah"
},
{
"id": "0"
}
]
Now I want all the "id" values in a single String object, separated by a separator.
For example, the above map should give me:
"12#Forty#0"
Note:
The order in which they are indexed in the list has to be maintained.
I know I can do it like this:
StringBuilder result = new StringBuilder();
for (Map map : myList) {
if (map.get("id") instanceof String) {
if(result.length()>0){
result.append('#');
}
result.append(map.get("id"));
}
}
//Use result.toString() for output
But I want a more readable and simplified code, preferably using Java stream api.
You can use stream and join all the key id values which are not null
String keyString = myList.stream()
.map(map->map.get("id"))
.filter(Objects::nonNull)
.map(Object::toString)
.collect(Collectors.joining("#"));
In case if you want to check if the value is String instance you can filter
filter(val-> val!=null && val instance String)
StringBuilder sb = new StringBuilder();
myList.stream().map((mapping) => {
sb.append(mapping.get(id))
sb.append("#")
}
You can add extra logic within the lambda function!
I am trying to create or update a JSON with a new key:value nodes inside a JsonArray.
So far I am able to add simple values using a map of nodes, but I am unable to add an array.
The goal is to create a JSON string with the following values:
{
"curfew": [{
"enabled": true,
"lock_time": "00:00",
"unlock_time": "00:10"
},
{
"enabled": true,
"lock_time": "00:20",
"unlock_time": "00:30"
}]
}
Starting from a new and empty JSON and later adding more values (such as the second "curfew" array).
Map<String, Object> values = ImmutableMap.of(
"enabled", true,
"lock_time", "00:00",
"unlock_time", "00:10");
String emptyJson = "{}"; //empty json
DocumentContext doc = getDocument(emptyJson)
doc.set(JsonPath.compile("$.curfew"), values).jsonString();
So far I am getting this (NOT AN ARRAY)
{
"curfew": {
"enabled": true,
"lock_time": "00:00",
"unlock_time": "05:00"
}
}
Create a List<Map<String, Object>> and then add your map in the list
List<Map<String, Object>> list = new ArrayList<>();
list.add(values);
And set the list in doc
doc.set(JsonPath.compile("$.curfew"), list).jsonString();
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);
{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
This is how my Json file looks .I m required to convert this json to a csv .(I m trying to convert a multi-dimesional data to 2d).I m using gson for my purpose.I cannot use gson.fromgson() function to object map with a template because it should be generic .
I know we can use CDL to convert jsonarray to csv format but It wont work in my case .
my csv format looks like
Employee*
empMID,comment.$,contact.address,contact.freetext,gender
mock:1,,2400 waterview,TRUE,male
mock:123,,2200 waterview,TRUE,female
colA#
TRUE
colB#
FALSE
I tried using google-GSON api to convert to this format .But I m not able to convert to this format .I have used * to represent its a json array and # to represent its a primitive type and contact.address to represent nested array inside another json array .I having problem relating this nested structure .I m able to traverse everything recursively like a column. Thanks in advance
public static void main(String[] args) throws IOException{
BufferedReader reader=null;
StringBuilder content=null;
String result=null;
reader = new BufferedReader(new FileReader("temp.json"));
String line = null;
content= new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
result= content.toString();
JsonElement jelement = new JsonParser().parse(result);
printJsonRecursive(jelement);
}
public static void printJsonRecursive(JsonElement jelement){
if(jelement.isJsonPrimitive()){
System.out.println(jelement.getAsString());
return;
}
if(jelement.isJsonArray()){
JsonArray jarray= jelement.getAsJsonArray();
for(int i=0;i<jarray.size();i++){
JsonElement element= jarray.get(i);
printJsonRecursive(element);
}
return;
}
JsonObject jobject= jelement.getAsJsonObject();
Set<Entry<String, JsonElement>> set= jobject.entrySet();
for (Entry<String, JsonElement> s : set) {
printJsonRecursive(s.getValue());
}
}
}
You can achieve this thru reflection if you have a object mapped to the json.
use gson/jackson to convert json to java object
append fields using reflection by iterating the class and get any field you interested in.
append value with reflection by getting value from the target object.
More detail look at my blog post below:
vcfvct.wordpress.com/2015/06/30/converting-nested-json-files-to-csv-in-java-with-reflection/
You are not printing the key. This should fix it.
for (Entry<String, JsonElement> s : set) {
System.out.println(s.getKey()); //Added
printJsonRecursive(s.getValue());
}
You can take care of \ns from here.
EDIT
If you want to print the keys just once for repeating json objects, create a Java bean to hold the data and populate it during your recursion. Once the bean is complete, add a method there to print all the data in the format you want (printing keys only once and so on).
You can use the library json2flat for converting your JSON to CSV.
This library doesn't require any POJO's. It simply takes your JSON as string and returns a 2D representation of it in the format of List<Object[]>.
For example for the JSON:
{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
It gives an output:
/cola,/colb,/Employee/empMID,/Employee/col1,/Employee/gender,/Employee/contact/address,/Employee/contact/freetext
,,"mock:1","something",,"2400 waterview",true
,,"mock:2","something",,"2200 waterview",true
false,false,,,,,
/**
* Get separated comlumns used a separator (comma, semi column, tab).
*
* #param headers The CSV headers
* #param map Map of key-value pairs contains the header and the value
*
* #return a string composed of columns separated by a specific separator.
*/
private static String getSeperatedColumns(Set<String> headers, Map<String, String> map, String separator) {
List<String> items = new ArrayList<String>();
for (String header : headers) {
String value = map.get(header) == null ? "" : map.get(header).replaceAll("[\\,\\;\\r\\n\\t\\s]+", " ");
items.add(value);
}
return StringUtils.join(items.toArray(), separator);
}