attach key name to value in a json array result - java

I have a code snippet in spring controller and DAO classes that fetches data from the database. The end result is to get a json output. When the result is processed, it displays just the array without displaying the name of the value-pair. Below is a snippet
dao class snippet
#SuppressWarnings("unchecked")
public List <Object[]> getResult(String no) {
List <Object[]> dataList = new ArrayList<>();
List <Object[]> results = sessionFactory.getCurrentSession().createQuery("select i.F_NO, i.LAST_NAME, i.FIRST_NAME, i.HOME_PHONE, i.SEX_NO from Data i where f_no = :f_no")
.setParameter("_no", no).list();
if(!CollectionUtils.isEmpty(results)){
Object firstDataOccurence = results.get(0);
dataList.add((Object[]) firstDataOccurence);
return dataList;
}
else{
return dataList;
}
}
controller snippet
#RequestMapping(value = "/getData/{tin}", method = RequestMethod.GET, headers = "Accept=application/json")
#ResponseBody
public List<Object[]> getData(#PathVariable("no") String searchName) {
searchName = searchName.trim();
List <Object[]> dataList= myDao.getResult(searchName);
return dataList;
}
now with the above my output becomes
[["100123","demo12","demo7","demo9","demo19","demo28","demo27","demo4","demo5","demo24","demo20"]]
with above result, u find out that the keyname is not there. Please how can I get a key:value pairs in my json response.

Step 1) Instead of Object list you can create a POJO and set the value
of db Object list to a pojo.
Step 2) You need to convert your normal list to JsonArray .Please
follow following steps to do so.
List <Object[]> results = sessionFactory.getCurrentSession().createQuery("select i.F_NO, i.LAST_NAME, i.FIRST_NAME, i.HOME_PHONE, i.SEX_NO from Data i where f_no = :f_no")
.setParameter("_no", no).list();
JSONObject jObject = new JSONObject();
try
{
JSONArray jArray = new JSONArray();
for (NewPojo obj: results)
{
JSONObject studentJSON = new JSONObject();
studentJSON.put("objfname", obj.getFName());
studentJSON.put("objlname ", obj.getLName());
jArray.put(studentJSON);
}
jObject.put("NewList", jArray);
} catch (JSONException jse) {
jse.printStacktrace();
}
Note : You can also use JSONObject also if you need
Ref links:
http://www.java2novice.com/java-json/javax.json/create-json-array/
How to Create JSONArray for a List<Class name>

Related

Want to match json key fields in a json object with items in arraylist and then delete the matching keys

I am relatively new to Java and cant seem to figure out what mistake I'm making.
I have a json object.
JSONObject json = new JSONObject();
json.put("alert_test","one");
json.put("Alert_testing","two");
json.put("name","admin");
I Have an arraylist which has just one element in it.
List<String> list = new ArrayList<>();
list.add("alert");
I have written a function to match the key in the json and object with the item in the array list and if the match is successful delete that key and update the jsonObject.
public static JSONObject jsonObjectDuplicateValues(JSONObject json, List<String> list){
JSONObject newJson= json;
list.forEach(name ->
json.keySet().forEach(keyStr ->
{
if(keyStr.toLowerCase().startsWith(name)){
json.remove(keyStr);
System.out.println(json.toString());
}
}));
System.out.println("outside foreach");
return newJson;
}
This is the function call:
JSONObject check = new JSONObject();
check = jsonObjectDuplicateValues(json,list);
System.out.println(check.toString());
The code gives an error inside the function call.
Help !

How to add two maps to the List

Code is:
How can to add the Map to the List
public List<Map<Object, Object>> getReportees(String idOfEmp) throws Exception {
JSONArray jsonarr_s = (JSONArray) jobj.get("list");
Map<Object, Object> map = new HashMap<Object, Object>();
if (jsonarr_s.size() > 0) {
// Get data for List array
for (int i = 0; i < jsonarr_s.size(); i++) {
JSONObject jsonobj_1 = (JSONObject) jsonarr_s.get(i);
JSONObject jive = (JSONObject) jsonobj_1.get("jive");
Object names = jsonobj_1.get("displayName");
Object userid = jive.get("username");
map.put(names, userid); //return the map with the key value pairs
map = new HashMap<Object, Object>();
String UserId = userid.toString();
String output1 = resp1.getEntity(String.class);
JSONObject jobjs = (JSONObject) new JSONParser().parse(output1);
// Store the JSON object in JSON array as objects (For level 1 array element i.e
// issues)
JSONArray jsonarr_new = (JSONArray) jobjs.get("issues");
int numofjiras = jsonarr_new.size(); //this jira count must be mapped to the name and id
map.put("count", numofjiras);
}
return map;
} else {
map.put("errorcheck", msg);
}
return map;
}
}
I want the output like:
Name id count
AJ 235457 2
Geet 637571 0
Actually I am getting the Name and id in key value pairs.Then I am trying to pass each id to an api which will give me the count.So how can I return all the fileds i.e Name ,id and count.So here I am trying to map like for this Userid and Name this is the count.How can we acheive it.Plesae help.Thanks in advnce.
I think you can try creating a new class to represent each row in your output. For example, you can create an Employee class like this:
public class Employee {
private long id;
private String name;
private int issueCount;
//getters and setters
}
You can, then, use this class and assign the values from the JSONArray arrays to it. Once you get the value for "count", you can just add the Employee object to the map (or list).
Hope this helps.
You would need to declare a local list first and then return that list:
public List<Map<Object, Object>> getReportees(String idOfEmp) throws Exception {
JSONArray jsonarr_s = (JSONArray) jobj.get("list");
Map<Object, Object> map = new HashMap<Object, Object>();
List<Map<Object, Object>> resultList = new ArrayList<Map<Object,Object>>();
if (jsonarr_s.size() > 0) {
// Get data for List array
for (int i = 0; i < jsonarr_s.size(); i++) {
JSONObject jsonobj_1 = (JSONObject) jsonarr_s.get(i);
JSONObject jive = (JSONObject) jsonobj_1.get("jive");
Object names = jsonobj_1.get("displayName");
Object userid = jive.get("username");
map.put(names, userid); //return the map with the key value pairs
String UserId = userid.toString();
String output1 = resp1.getEntity(String.class);
JSONObject jobjs = (JSONObject) new JSONParser().parse(output1);
// Store the JSON object in JSON array as objects (For level 1 array element i.e
// issues)
JSONArray jsonarr_new = (JSONArray) jobjs.get("issues");
int numofjiras = jsonarr_new.size(); //this jira count must be mapped to the name and id
map.put("count", numofjiras);
}
resultList.add(map);
} else {
map.put("errorcheck", msg);
resultList.add(map);
}
return resultList;
}
Based on your results though you should consider flipping your data objects to instead be
Map<Object, List<Object>>
where the first Object in the map which is they key the name and then the list would contain two objects [id, count].

Java get specific value from list and add to other list

i want to ask some question, how to get specific value from list and add to another list, lets say i have list (this is cust list from hibernate DAO) like:
[["marketplace","001-002-003"],["insurance","142-523-132"],["car purchase","982349824"]]
i just want to get a value of "marketplace","insurance", and "car purchase" from that list and add to new list called "bu"
here is my code
public #ResponseBody String findBU(#RequestBody AllCustomerHist customer){
BigDecimal id= customer.getId();
String message;
List<String> bu= new ArrayList<>();
int i;
System.out.println("ID = "+id);
List<AllCustomerHist> cust = allCustomerHistService.findBU(id);
for (i=0; i<cust.size(); i++){
System.out.println("iteration = "+i);
// stumbled here //
}
JSONObject json = new JSONObject();
json.put("id", id);
json.put("BU", bu);
message = json.toString();
return message;
}
this is my AllCustomerHistDaoImpl class
//release 1.3
#SuppressWarnings("unchecked")
public List<AllCustomerHist> findBU(BigDecimal adpId) {
// TODO cek kodingan
Criteria criteria = getSession().createCriteria(AllCustomerHist.class)
.setProjection(Projections.projectionList()
.add(Projections.property("srctable"), "srctable")
.add(Projections.property("customerId"), "customerId"))
.add(Restrictions.eq("adpId", adpId));
return (List<AllCustomerHist>)criteria.list();
}
Notice that AllCustomerHist is an entity class to define the table in hibernate
thank you for your helps :D
Since you need to make some validation and you need to take off the whole AllCustomerHistobject what I would do is the following code
List<AllCustomerHist> cust = allCustomerHistService.findBU(id);
List<String> bu = new ArrayList<String>(cust.size());
for (i=0; i<cust.size(); i++){
System.out.println("iteration = "+i);
AllCustomerHist aCust = cust.get(i);
bu.add(aCust.getSrctable());
}
//here your bu list should be ready to be used.....
I hope it's what you needed
If you use JDK1.8+, you can also do it like this:
List<AllCustomerHist> cust = allCustomerHistService.findBU(id);
List<String> bu = cust.stream()
.map(AllCustomerHist::getSrctable)
.collect(Collectors.toList());

How to modify the JSON data and return the updated JSON data

We have a requirement to update the JSON data in middle and need to return the updated JSON data using java. Also it should support any type of JSON data.
ex:
Assume {object:{"color":"red","shape":"Triangle"}} is the JSON data and in this we need to update the shape value to Rectangle and we need to return the updated JSON data as below:
{object:{"color":"red","shape":"Rectangle"}}
For this we need to pass the element path ( which element we need to update) and updateText and JSON Data to the JAVA code.
here is the methodCall:
updateValue("object/shape", "Rectangle", "{object:{"color":"red","shape":"Triangle"}}")
We tried below code using Gson library. But with this code we are able to update the targeted Json element, but the requirement is to return the entire JSON data with the updated value.
So please suggest how do we re-build the JSON data with the updated text.
Below is the code we tried to update the Json Data.
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
String result = "";
for(String key : keys)
{
if (jsonObject.get(key) instanceof JsonObject)
{
jsonObject = (JsonObject)jsonObject.get(key);
}
else if(jsonObject.get(key) instanceof JsonArray)
{
JsonArray jsonArray = (JsonArray)jsonObject.get(key);
result = jsonArray.toString();
}
else
{
result = jsonObject.get(key).toString();
}
}
result = result.replace(result, updateText);
return result;
}
The problem lies in the way you do the replacements. When you translate the JsonObject to String, you lose the object, and after replacement, you just have the replaced String. To fix it, you need to operate directly on the object, instead of the String counterpart. Because JsonObject is mutable, holding a reference to the input will reflect the changes. One drawback is you can't replace a value in a JsonArray this way, partly because you don't know which element to replace. To accomplish that, you will need a little more in the input(either the value to replace or the element position).
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
JsonObject returnVal = jsonObject; // This holds the ref to target json object
JsonPrimitive jp = new JsonPrimitive(updateText);
String finalKey = keys[keys.length - 1];
for(String key : keys)
{
if (jsonObject.get(key).isJsonObject())
{
jsonObject = (JsonObject)jsonObject.get(key);
}
}
jsonObject.remove(finalKey);
jsonObject.add(finalKey, jp);
return returnVal.toString();
}
You can use JsonPath lib for that and try using the following code.
private static final Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
JsonNode updatedJson = JsonPath.using(configuration).parse(originaljson)
.set("use the path to go for value", "new value").json();
json = updatedJson.toString();

Convert JSON object with duplicate keys to JSON array

I have a JSON string that I get from a database which contains repeated keys. I want to remove the repeated keys by combining their values into an array.
For example
Input
{
"a":"b",
"c":"d",
"c":"e",
"f":"g"
}
Output
{
"a":"b",
"c":["d","e"],
"f":"g"
}
The actual data is a large file that may be nested. I will not know ahead of time what or how many pairs there are.
I need to use Java for this. org.json throws an exception because of the repeated keys, gson can parse the string but each repeated key overwrites the last one. I need to keep all the data.
If possible, I'd like to do this without editing any library code
As of today the org.json library version 20170516 provides accumulate() method that stores the duplicate key entries into JSONArray
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("a", "b");
jsonObject.accumulate("c", "d");
jsonObject.accumulate("c", "e");
jsonObject.accumulate("f", "g");
System.out.println(jsonObject);
Output:
{
"a":"b",
"c":["d","e"],
"f":"g"
}
I want to remove the repeated keys by combining their values into an array.
Think other than JSON parsing library. It's very simple Java Program using String.split() method that convert Json String into Map<String, List<String>> without using any library.
Sample code:
String jsonString = ...
// remove enclosing braces and double quotes
jsonString = jsonString.substring(2, jsonString.length() - 2);
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String values : jsonString.split("\",\"")) {
String[] keyValue = values.split("\":\"");
String key = keyValue[0];
String value = keyValue[1];
if (!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(value);
}
output:
{
"f": ["g"],
"c": ["d","e"],
"a": ["b"]
}
In order to accomplish what you want, you need to create some sort of custom class since JSON cannot technically have 2 values at one key. Below is an example:
public class SomeClass {
Map<String, List<Object>> values = new HashMap<String, List<Object>>();
public void add(String key, Object o) {
List<Object> value = new ArrayList<Object>();
if (values.containsKey(key)) {
value = values.get(key);
}
value.add(o);
values.put(key, value);
}
public JSONObject toJson() throws JSONException {
JSONObject json = new JSONObject();
JSONArray tempArray = null;
for (Entry<String, List<Object>> en : values.entrySet()) {
tempArray = new JSONArray();
for (Object o : en.getValue()) {
tempArray.add(o);
}
json.put(en.getKey(), tempArray);
}
return json;
}
}
You can then retrieve the values from the database, call the .add(String key, Object o) function with the column name from the database, and the value (as the Object param). Then call .toJson() when you are finished.
Thanks to Mike Elofson and Braj for helping me in the right direction. I only wanted to have the keys with multiple values become arrays so I had to modify the code a bit. Eventually I want it to work for nested JSON as well, as it currently assumes it is flat. However, the following code works for what I need it for at the moment.
public static String repeatedKeysToArrays(String jsonIn) throws JSONException
{
//This assumes that the json is flat
String jsonString = jsonIn.substring(2, jsonIn.length() - 2);
JSONObject obj = new JSONObject();
for (String values : jsonString.split("\",\"")) {
String[] keyValue = values.split("\":\"");
String key = keyValue[0];
String value = "";
if (keyValue.length>1) value = keyValue[1];
if (!obj.has(key)) {
obj.put(key, value);
} else {
Object Oold = obj.get(key);
ArrayList<String> newlist = new ArrayList<String>();
//Try to cast as JSONArray. Otherwise, assume it is a String
if (Oold.getClass().equals(JSONArray.class)) {
JSONArray old = (JSONArray)Oold;
//Build replacement value
for (int i=0; i<old.length(); i++) {
newlist.add( old.getString(i) );
}
}
else if (Oold.getClass().equals(String.class)) newlist = new ArrayList<String>(Arrays.asList(new String[] {(String)Oold}));
newlist.add(value);
JSONArray newarr = new JSONArray( newlist );
obj.put(key,newarr);
}
}
return obj.toString();
}

Categories