How to convert Optional<JsonObject> to List<String> - java

I have some api parameters which I have received from a json file in test method. Now I need to convert this object to a list, because it contains arrays that I would like to handle individually.
#SuppressWarnings("unchecked")
static Optional getQueryParametersTEST(JsonObject inputJsonObject) {
JsonObject operators = inputJsonObject.getJsonObject("operators");
JsonObject tez = operators.getJsonObject("tez");
JsonArray parameters = tez.getJsonArray("parameters");
Optional<JsonObject> queryParameters = parameters.stream().
filter(JsonObject.class::isInstance).
map(JsonObject.class::cast).
filter(jsonObject -> jsonObject.getJsonObject("queryParameters") != null).
map(item -> item.getJsonObject("queryParameters")).
findFirst();
return queryParameters;
}
after i received queryParameters it comes in this format
Optional[{"priceMin":["0"],"priceMax":["150000"],"currency":["5561"],"hotelClassId":[""],"accommodationId":["158525","9002884","1"],"rAndBId":["15350","2424","2474","2749","5737","5738"]}
What can i do to get a list of Strings
I tried to perform a
return queryParameters.ifPresent(newList::add)
.flatMap(Optional::stream)
.collect(Collectors.toList());
Tried using this but Jsonobject requires a source of string but i have queryParameters of type Optional queryParameters
JSONObject obj = new JSONObject(my source should be the query param )
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}

Related

Parse JSON in java (custom)

I have a JSON array in the following format:
[["1234","OS","01/31/2023","02/01/2023","First Day"],["1245","OS","01/23/2023","01/24/2023","Last Day"],["3411","OS","09/21/2022","09/21/2022","Second Day"]]
In Java, I would like to parse this array and store data in the following format:
String[] firstElements = ["1234" , "1245", "3411"];
String[] secondElements = ["OS", "OS", "OS"];
String[] thirdElements = ["01/31/2023", "01/23/2023", "09/21/2022"];
String[] fourthElements = ["02/01/2023", "01/24/2023", "09/21/2022"];
String[] fifthElements = ["First Day", "Last Day", "Second Day"];
Is this possible? How can I achieve this?
String jsonArray = "[[\"1234\",\"OS\",\"01/31/2023\",\"02/01/2023\",\"First Day\"],[\"1245\",\"OS\",\"01/23/2023\",\"01/24/2023\",\"Last Day\"],[\"3411\",\"OS\",\"09/21/2022\",\"09/21/2022\",\"Second Day\"]]";
JsonArray array = Json.createReader(new StringReader(jsonArray)).readArray();
List<String> firstElements = new ArrayList<>();
List<String> secondElements = new ArrayList<>();
List<String> thirdElements = new ArrayList<>();
List<String> fourthElements = new ArrayList<>();
List<String> fifthElements = new ArrayList<>();
array.forEach( value -> {
JsonArray innerArray = value.asJsonArray();
firstElements.add(innerArray.getString(0));
secondElements.add(innerArray.getString(1));
thirdElements.add(innerArray.getString(2));
fourthElements.add(innerArray.getString(3));
fifthElements.add(innerArray.getString(4));
)};
If you want something more generic you can use a List<List<String>>
String jsonArray = "[[\"1234\",\"OS\",\"01/31/2023\",\"02/01/2023\",\"First Day\"],[\"1245\",\"OS\",\"01/23/2023\",\"01/24/2023\",\"Last Day\"],[\"3411\",\"OS\",\"09/21/2022\",\"09/21/2022\",\"Second Day\"]]";
JsonArray array = Json.createReader(new StringReader(jsonArray)).readArray();
List<List<String>> elements = new ArrayList<>();
array.forEach( value -> {
JsonArray innerArray = value.asJsonArray();
List<String> subElements = new ArrayList<>();
for (int i = 0; i < innerArray.size(); i++) {
subElements.add(innerArray.getString(i));
}
elements.add(subElements);
});
There are a few solutions to parsing JSON from Java, like GSON, though if the data format you are working with is simple enough and you don't have to parse all kinds of JSON, you might as well parse it by yourself.

Serializing JSON To Spring RequestBody with int array

I have a Spring controller method that specifies a #RequestBody as a parameter. The class for the request body looks something like this
public class myClass {
CustomObject obj
int x
int y
int[] values
Character c
//getters and setters
}
I'm writing unit tests and am having trouble setting the int[] values element through a normal JSONobject. I would prefer not to use a JSONArray if possible, as the other elements are passed through just fine through a JSONObject as follows:
JSONObject requestParams = new JSONObject();
if(obj != null)
requestParams.put("obj", obj);
if(c != null)
requestParams.put("c", c);
I've tried requestParams.put("values", Arrays.toString(values)) where values is defined as int[] values = new int[]{10,20,30,40,50,60,10,15,20,30,40,55} but am still getting a 400 error when I try to send the request, only when values is not null.
How do I send this list of values to the RequestBody class through a JSONObject?
You can use like below:
//prepare list
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
...
list.add(100);
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
obj.put("values", array);
}catch(JSONException ee){
}
above is simlified way you can reduce boiler plate code.
you can't parse array to object,try to parse to ArrayNode using ObjectMapper:
int[] values = new int[]{10,20,30,40,50,60,10,15,20,30,40,55};
ObjectMapper mapper = new ObjectMapper();
ArrayNode node = mapper.valueToTree(values);

JSON Parsing in Java Webservice of multiple JSONObjects in JSONObject

This is my JSON string,
{
"listmain":{
"16":[{"brandid":"186"},{"brandid":"146"},{"brandid":"15"}],
"17":[{"brandid":"1"}],
"18":[{"brandid":"12"},{"brandid":"186"}],
}
}
I need to get values in "16","17","18" tag and add values and ids("16","17","18") to two ArrayList.
What i meant is,
when we take "16", the following process should happen,
List<String> lsubid = new ArrayList<String>();
List<String> lbrandid = new ArrayList<String>();
for(int i=0;i<number of elements in "16";i++) {
lsubid.add("16");
lbrandid.add("ith value in tag "16" ");
}
finally the values in lsubid will be---> [16,16,16]
the values in lbrandid will be---> [186,146,15]
Can anyone please help me to complete this.
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
You can parse the JSON like this
JSONObject responseDataObj = new JSONObject(responseData);
JSONObject listMainObj = responseDataObj.getJSONObject("listmain");
Iterator keys = listMainObj.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
//store key in an arraylist which is 16,17,...
// get the value of the dynamic key
JSONArray currentDynamicValue = listMainObj.getJSONArray(currentDynamicKey);
int jsonrraySize = currentDynamicValue.length();
if(jsonrraySize > 0) {
for (int i = 0; i < jsonrraySize; i++) {
JSONObject brandidObj = currentDynamicValue.getJSONObject(i);
String brandid = brandidObj.getString("brandid");
System.out.print("Brandid = " + brandid);
//store brandid in an arraylist
}
}
}
Source of this answer

Issue With JSON Object in Java?

I have a JSON Object which converted into String and saved into database .But when i am trying to get it back it is throwing exception.My object is something like that...
{"COLUMN":["Type","Sub Type","F.P.","P.P.","Process","Due To Start"]}
How can we get the data back in Normal form?
My Java Code is.....
JSONObject obj = new JSONObject();
JSONArray the_json_array = obj.getJSONArray(userReorderOption);
int size = the_json_array.size();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
arrays.add(another_json_object);
}
And Exception i am getting....
net.sf.json.JSONException: JSONObject["{\"TASKLIST_COLUMN_REORDER\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}"] is not a JSONArray.
And this is java Code how i am creating JSON Object and saving into database...
String userReorderSelection;
Set set = new LinkedHashSet(userReorderSelection);
JSONObject json = new JSONObject();
json.accumulate("COLUMN", set);
saveJSONObj("PrimaryKeyColumn", json.toString());
Thanks Tichodroma,
But as i told i am using net.sf.json.JSONObject class and above things we can achieve from this class too..What i did to solve the above issue?...Please have a look on the Java code...
JSONObject jsonObj = new JSONObject();
JSONObject obj = jsonObj.fromObject(userReorderOption);
JSONArray columnName = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < columnName.size(); i++) {
System.out.println(columnName.getString(i));
}
This code work fine for me with my Json Jar**(net.sf.json)**
Your JSON is not a JSONArray.
A JSONArray is an ordered sequence of values.
You have a JSONObject.
A JSONObject is an unordered collection of name/value pairs.
Edit:
Using the JSON implementation from org.codehaus.jettison.json, you can do this:
String json = "{\"COLUMN\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}";
JSONObject obj = new JSONObject(json);
JSONArray column = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < column.length(); i++) {
final String field = column.getString(i);
System.out.println(field);
}
Result:
Type
Sub Type
F.P.
P.P.
Process
Due To Start

How to parse a JSONArray of JSONObjects in JAVA?

I have the following array returned to my JAVA Android application from PHP:
Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );
In Java they above array looks like this:
{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};
For a simple JSONObject I'm using:
JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);
referral_fullname = finalResult.getString("referral_fullname");
but for an array of objects I don't know!
String str = your Json-> apply to.String();
JSONObject jObject = new JSONObject(str);
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObject .getString(key);
map.put(key,value);
}
Your Json Syntax is wrong , JSONArray should be like this :
["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];
and to parse a JsonArray that contains some JSONObject , try this :
//parse the result
JSONObject jsonResult = null;
JSONArray arrayResult = null;
ArrayList<YourObject> listObjects = null;
try {
arrayResult = new JSONArray(result);
if(arrayResult != null) {
listObjects = new ArrayList<YourObject>();
int lenght = arrayResult.length();
for(int i=0; i< lenght; i++) {
JSONObject obj = arrayResult.getJSONObject(i);
YourObject object = new YourObject(obj);
listObjects.add(object);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
And add a constructor in your Class YourObject to convert your Json to an instance :
public YourObject(JSONObject json) {
if (!json.isNull("referral_fullname"))
this.referral_fullname = json.optString("referral_fullname", null);
if (!json.isNull("referral_balance"))
this.referral_balance = json.optString("referral_balance", null);
}
You should use
JSONArray finalResult = new JSONArray(tokener);
if you can. You structure is now an object with two fields, 0 and 1, which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like
JSONObject jso;
for(int i = finalResult.lenght-1; i >=0; i--){
jso = finalResult.get(i);
// jso == {"referral_fullname":"Name 1","referral_balance":"500"}
[whatever]
}
Try this.............
final JSONArray result_array = json.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject joObject = result_array.getJSONObject(i);
String jName = joObject.get("referral_fullname").toString();
String jbalance = joObject.get("referral_balance").toString();
}
First make an JSON object and see then in inner level what you have if you have array then fetch array.
You need to make JSON object first. For example, if resp is a String (for example coming as http response)
JSONObject jsonObject = new JSONObject(resp);
jsonObject may contains other JSON Objects or JSON array. How to convert the JSON depends on the response.
If arraykey is a array inside the JSON objects then we can get list of array by the following way.
JSONArray arr = jsonObject.getJSONArray("arraykey");
Check the length of arr, if it is greater than 0 then it contains JSON objects or JSON array depending the data.
There is a complete example with some explanation about JSON String to JSON array can be found at
http://www.hemelix.com/JSONHandling

Categories