Get jsonArray Using Native query entity manager - java

I have an service class as below:
public class RulesService {
#PersistenceContext
private EntityManager em;
public JSONArray getReportingTableData(String Query) {
List<Object> list = em.createNativeQuery(Query).getResultList();
return /*convert the above list as json array**/;
}
}
So, if the query is "select col1 as name,col2 as agefrom table1" then my jsonArray should be
[{"name":"test","age":"24"},{"name":"test1","age":"26"}]
I don't want to use pojo or entity class here, because the query will get change dynamically and there are many number of tables here, so I don't want to create seperate java class for each table.That is the reason am trying to make it as a JSONArray.
Can anyone please give me the right solution do it.

You could do that with Jackson's ObjectMapper. This tutorial is very interesting.
List<Object> list = em.createNativeQuery(Query).getResultList();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, list);
final byte[] data = out.toByteArray();
System.out.println(new String(data));

you can use ObjectMapper to do dynamically.
public JSONArray getReportingTableData(String Query) {
List<Object> list = em.createNativeQuery(Query).getResultList();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
String arrayToJson = objectMapper.writeValueAsString(list);
JSONArray array = new JSONArray(arrayToJson);
return /*convert the above list as json array**/;
}

I guess you want to do like bellow. your query result is list of array. [["test","24"],["test2","26"]] and you want to convert it to key-value
List<Map<String,String>> result = listOfarray.stream()
.map(arr->{
Map<String,String> map = new HashMap<>();
map.put("name",arr[0]);
map.put("age",arr[1]);
return map;
})
.collect(Collectors.toList());

Sorry guys, I might be late but someone might find this interesting and save his/her day.
Reference
[https://gist.github.com/baxtheman/44fd1601380d415eeec53d9e6d5587dc][1]
public List<ObjectNode> getQuery(
Integer anno,
Integer settimana) {
Query q = em.createNativeQuery(
"NATIVE SQL....",Tuple.class);
List<Tuple> results = q.getResultList();
List<ObjectNode> json = _toJson(results);
return json;
}
private List<ObjectNode> _toJson(List<Tuple> results) {
List<ObjectNode> json = new ArrayList<ObjectNode>();
ObjectMapper mapper = new ObjectMapper();
for (Tuple t : results)
{
List<TupleElement<?>> cols = t.getElements();
ObjectNode one = mapper.createObjectNode();
for (TupleElement col : cols)
{
one.put(col.getAlias(), t.get(col.getAlias()).toString());
}
json.add(one);
}
return json;
}

Its a late answer but got it when i needed it.
The pretty easy and simple thing worked for me is
String[] columns = {"id","name","salary","phone","address", "dob"};
String query = "SELECT id,name,salary,phone,address,dob from users ";
List<Object[]> queryResp = em.createNativeQuery(query).getResultList();
List<Map<String,String>> dataList = new ArrayList<>();
for(Object[] obj : queryResp) {
Map<String,String> row = new HashMap<>(columns.length);
for(int i=0; i<columns.length; i++) {
if(obj[i]!=null)
row.put(columns[i], obj[i].toString());
else
row.put(columns[i], "");
}
dataList.add(row);
}
//Creating the ObjectMapper object
ObjectMapper mapper = new ObjectMapper();
//Converting the Object to JSONString
String jsonString = mapper.writeValueAsString(dataList);

Related

jackson - read specific field from string list of jsons

I'm pretty new to world of jackson, and wanted to read the value of specific field from list of jsons (which is a response body of third-party api).
for a single json, using objectMapper works fine.
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(sampleString);
JsonNode idNode = rootNode.path("id");
System.out.println("id: "+ idNode.asText());
But I want to parse list of jsons (which is a string coming from a response body)
.So for example I receive this body:
[
{
"id":10,
"firstName":"Jack",
"primaryPhone":"9999999999",
"email":"jack#me.com"
},
{
"id":4,
"firstName":"Mark",
"primaryPhone":"9999999991",
"email":"mark#me.com"
},
{
"id":12,
"firstName":"Susaan",
"primaryPhone":"9999999992",
"email":"susan23#me.com"
}
]
I want to read the ids first, and if I find a specific id, return some other info from that block.
For example if id=4, read the firstName and email of that person.
But I'm not sure how to parsee list of json.
Any suggestions/comments is appreciated.
You can try,
JsonNode array = objectMapper.readValue(sampleString, JsonNode.class);
for(int i=0;i<array.length;i++){
JsonNode jsonNode = array.get(i);
JsonNode idNode = jsonNode.get("id");
String id = idNode.asText();
if(id.equals("4")){
JsonNode firstNameNode = jsonNode.get("firstName");
String firstName = firstNameNode.asText();
System.out.println("firstName = " + firstName);
JsonNode emailNode = jsonNode.get("email");
String email = emailNode.asText();
System.out.println("email = " + email);
break;
}
}
You can use Json Path.
So, the query would be something like this:
$[?(#.id == 4)].firstName
You can create a POJO like the one below:
class Record {
private Long id;
private String firstName;
//Getters and setters
}
And deserialise the json into List of these POJOS, e.g.:
ObjectMapper mapper = new ObjectMapper();
List<Record> records = mapper.readValue("", new TypeReference<List<Record>>() { });
Once done, you can filter out the records with stream, e.g.:
List<Record> filtered = records.stream()
.filter(r -> r.getId() = 12)
.collect(Collectors.toList());

How to convert Arraylist consisting of pojo class into array in java

I have a pojo class named "Performance" like this
public class Performance {
String productId;
String productBrand;
String productGraph;
//getters and setters
And I saved it to arraylist named "performanceList" like this:
JSONArray dataGraph=null;
JSONObject obj = new JSONObject(response);
dataGraph = obj.getJSONArray("product_list");
performanceList.clear();
for(int i=0;i<dataGraph.length(); i++){
JSONObject jsonObject = dataGraph.getJSONObject(i);
Performance performance = new Performance();
if(!jsonObject.isNull("id")){
performance.setProductId(jsonObject.getString("id"));
}
if(!jsonObject.isNull("brand")) {
performance.setProductBrand(jsonObject.getString("brand"));
}
if(!jsonObject.isNull("sales")){
performance.setProductGraph(jsonObject.getString("sales"));
}
performanceList.add(i, performance);
}
And now, can you please help me fetch the data from arraylist and be converted into array just like this
String []brand = {/*getProductBrand from arraylist*/};
String []id = {/*getProductId from arraylist*/};
String []id = {/*getProductGraph from arraylist*/};
Use foreach or for loop
String[] brand = new String[performanceList.size()];
for(int i=0;i<performanceList.size();i++)
{
brand[i] = performanceList.get(i).getBrand();
.....
......
}
Similary for other fields as well.
you could use stream.map() in java8
List<String> productBrands = performanceList
.stream()
.map(el-> el.getProductBrand())
.collect(Collectors.toList());
repeat same for el.getId() or any other data you need to collect from Performance objects

what is the best way to convert resultset to json [duplicate]

This question already has answers here:
Most efficient conversion of ResultSet to JSON?
(14 answers)
Closed 3 years ago.
I am getting the Resultset from mySQL server, and want to send it as JSON back to the client..
the server is writen in Java EE..
I have been looking up a lot for this.. but nothing simple..
is that elementary process really has to be that hard?
or is there anything wrong in my understanding?
Use Jackson for JSON-processing. If you convert your results to a POJO simply make the POJO Jackson compatible (getters will be serialized automatically for instance or use #JsonProperty.
Example for converting a pojo to JSON:
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(somePojo);
If you do not convert your results to a POJO the JsonNode subclass called ObjectNode can be used.
Example:
public String convert(ResultSet rs) {
ObjectNode node = new ObjectMapper().createObjectNode();
node.put("fieldName", rs.getString("columnName"));
return node.toString(); // this is proper JSON
}
However, the most common and clean approach is to return a POJO from your function (whether it is an EJB or a REST service or similar) and then let the framework convert it to JSON for you (typically the framework uses Jackson). This means that your method simply returns some kind of model object that is Jackson compatible.
https://gist.github.com/mreynolds/603526
public String convertResultSetToJson(ResultSet resultSet) throws SQLException {
Joiner commaJoiner = Joiner.on(", \n");
StringBuilder builder = new StringBuilder();
builder.append("{ \"results\": [ ");
List<String> results = new ArrayList<String>();
while (resultSet.next()) {
List<String> resultBits = new ArrayList<String>();
ResultSetMetaData metaData = resultSet.getMetaData();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
StringBuilder resultBit = new StringBuilder();
String columnName = metaData.getColumnName(i);
resultBit.append("\"").append(columnName).append("\": \"").append(resultSet.getString(i)).append("\"");
resultBits.add(resultBit.toString());
}
results.add(" { " + commaJoiner.join(resultBits) + " } ");
}
builder.append(commaJoiner.join(results));
builder.append("] }");
return builder.toString();
}
You may use JSONObject provided by org.json.
Import org.json.JSONObject into your file. Then you can convert the resultset as follows:
jsonObject = new JSONObject();
jsonObject.put(key,resultSet.getInt(resultSet.findColumn(columname)));
return jsonObject.toString();
So if you wanted to return a column with name NO_OF_DAYS having value 3 into a json object such as this {"days" : "3"}, you write the code as:
jsonObject.put("days",resultSet.getInt(resultSet.findColumn("NO_OF_DAYS")));
#SuppressWarnings("unchecked") //we use 3rd-party non-type-safe types...
public static String convertResultSetToJson(ResultSet resultSet) throws SQLException
{
JSONArray json = new JSONArray();
ResultSetMetaData metadata = resultSet.getMetaData();
int numColumns = metadata.getColumnCount();
while(resultSet.next()) //iterate rows
{
JSONObject obj = new JSONObject(); //extends HashMap
for (int i = 1; i <= numColumns; ++i) //iterate columns
{
String column_name = metadata.getColumnName(i);
obj.put(column_name, resultSet.getObject(column_name));
}
json.add(obj);
}
return json.toJSONString();
}
source: https://github.com/OhadR/ohadr.common/blob/master/src/main/java/com/ohadr/common/utils/JsonUtils.java
you can use easily: JsonUtils.convertResultSetToJson(...)
Grab the JAR from Maven Central,
<!-- https://mvnrepository.com/artifact/com.ohadr/ohadr.commons -->
<dependency>
<groupId>com.ohadr</groupId>
<artifactId>ohadr.commons</artifactId>
<version>0.3</version>
</dependency>

How to retrieve a POJO from MongoDB via a Generic Class

I'm new to Mongo, and am trying to use it to implement a cache internally in our application. We have a defined cache interface (public Cache(K, V) ) with several alternative implementations (HashTable, JCS etc). I need to create a MongoDB implementation for some hard (i.e. expensive) to calculate data. The cache data will either be a POJO or a List of POJO's.
My problem is getting the Mongo response back into a POJO or (the bit that's eluded me so far), into a List of POJOs.
Code so far:
public class MongoDBCache<K, V> implements Cache<K, V>
{
private String name = null;
public MongoDBCache(String name)
{
this.name = name;
}
public V get(K key)
{
V result = null;
try
{
DB mdb = getMongoDB();
DBCollection mcol = mdb.getCollection(name);
BasicDBObject query = new BasicDBObject("_id", key.toString());
DBCursor cursor = mcol.find(query);
if (cursor.hasNext())
{
Gson gson = new Gson();
DBObject dbobj = cursor.next();
Class type = ????;
result = (V) gson.fromJson(dbobj.get("obj").toString(), type);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
}
I can kind of make this work if the value is just a POJO (can get the type on the put method, not ideal but works), but I can't figure out how to make it work for a List. As an example, a ArrayList<Long> ends up as ArrayList<Double>.
Any suggestions? Something I can do in GSON? Something I can do with reflection? (I'm not tied into GSON, or any other library, this is just my current attempt).
Thanks,
Alan
If you could save also your class type into the database along with the object, you could infer the right class using something like:
if (cursor.hasNext())
{
Gson gson = new Gson();
DBObject dbobj = cursor.next();
Class type = Class.forName(dbobj.get("class").toString());
result = (V) gson.fromJson(dbobj.get("obj").toString(), type);
}
you can get the proper string with code like this:
SomeClass object = ...
Class c = object.getClass();
String cn = c.toString();
Edit
Pay attention that when you want to store on database the class type and you are dealing with generics, due to type erasure, you cannot do something like this:
ArrayList<Long> l = new ArrayList<Long>();
String clazz = l.getClass
since clazz will store:
java.util.ArrayList
instead you need to do something like this
Type listType = new TypeToken<ArrayList<Long>>() {}.getType();
String clazz = l.getClass();
that will return you:
java.util.ArrayList<java.lang.Long>

How separate keys and values in this JSON object, using Java?

I have JSON object like
{
"projector":"no",
"video_conference":"no",
"polycom":"no",
"lcd":"no",
"digital_phone":"no",
"speaker_phone":"no"
}
How do I store the keys in one array and the values in a separate array?
Try GSON for converting your java object to json and vice versa.
Refer this link
http://code.google.com/p/google-gson/
You may try this.
String s = " { "projector":"no", "video_conference":"no", "polycom":"no", "lcd":"no", "digital_phone":"no", "speaker_phone":"no" }";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("projector");
Iterator iter = menu.keys();
String[] keyArr = new String();
String[] valArr = new String();
int count = 0;
while(iter.hasNext()){
keyArr[count] = (String)iter.next();
valArr[count] = menu.getString(key);
count +=1;
}
I like Jackson from http://codehaus.org/ for JSON parsing.
String text = "{ \"projector\":\"no\", \"video_conference\":\"no\", \"polycom\":\"no\", \"lcd\":\"no\", \"digital_phone\":\"no\", \"speaker_phone\":\"no\" }";
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(text, Map.class);
Set<String> k = map.keySet();
Collection<Object> v = map.values();
String[] keys = k.toArray(new String[k.size()]);
String[] values = v.toArray(new String[v.size()]);

Categories

Resources