Fetching values and sending in an array - java

I have fetched some integer values from getAPI:
List<String> jsonResponse = response.jsonPath().getList("$");
for (int i = 0; i < jsonResponse.size(); i++) {
if (getJsonPath(response, "type[" + i + "]").equals("agent_sms_missed_call")) {
agentMissedCallId = getJsonPath(response, "id[" + i + "]");
break;
}
}
for (int i = 0; i < jsonResponse.size(); i++) {
if (getJsonPath(response, "type[" + i + "]").equals("caller_sms_missed_call")) {
callerMissedCallSmsId = getJsonPath(response, "id[" + i + "]");
break;
}
}
Now I want to send the value of agentMissedCallId and callerMissedCallSmsId in PUT API : How can i acheive that .
{
"sms_template": [
idFetched(agentMissedCallId), idFetched(callerMissedCallSmsId)
]
}
Response I am getting from a GET API :
[
{
"id": 29169,
"name": "Template 1",
"type": "agent_sms_missed_call"
},
{
"id": 29170,
"name": "Template 2",
"type": "caller_sms_missed_call"
}
]
Request body I want :
{
"sms_template": [
29169
],
"name": "Hello ",
"destination": "hangup||1",
"description": "number for department"
}

This below approach is not recommended, but it doesn't require any 3rd lib, so I think it works for you.
Map<String, Object> body = new LinkedHashMap<>();
body.put("sms_template", List.of(agentMissedCallId, callerMissedCallSmsId));
body.put("name", "Hello ");
body.put("destination", "hangup||1");
body.put("description", "number for department");
given().log().body().contentType(ContentType.JSON)
.body(body)
.post("https://postman-echo.com/post");

Related

Java parse json file JSONObject

I have json file with such form:
{
"Region_1": {
"Area_1": {
"id": "id_1",
"email": "email_1"
},
"Area_2": {
"id": "id_2",
"email": "email_2"
}
},
"Region_2": {
"Area_1": {
"id": "id_1",
"email": "email_1"
},
"Area_2": {
"id": "id_2",
"email": "email_2"
}
}
}
I need to parse this structure using JSONObject, I have already code which parse this but not get Region_2 only.
Region_1 getting.
JSONObject obj = new JSONObject(fileData);
for (Map.Entry<String, Object> entry : obj.entrySet()) {
String region = entry.getKey().toString();
JSONObject areas = new JSONObject(entry.getValue().toString());
System.out.println("region: " + region);
List links = areas.entrySet().collect({ it ->
String area = it.getKey().toString();
System.out.println("area: " + area);
JSONObject areaData = new JSONObject(it.getValue().toString());
String code = areaData.getString("id");
String email = areaData.getString("email");
System.out.println("code: " + code.toString());
System.out.println("email: " + email.toString());
})
}
Why only first object takes from json file ?

How to rearrange json objects within json structure itself? Java

Im trying to restructure duplicate json values in my JSON Structure and rearrange them using the simplest possible method.
I got to the point where I managed to get it stored in a map each time it loops over the JSONObject but from here how do I proceed to store the mapping to achieve my desired outcome? Thank you so much in advance.
public static void main(String[] args) throws JSONException {
String jsonString = "[{\"file\":[{\"fileRefNo\":\"AG/CSD/1\",\"status\":\"Active\"}],\"requestNo\":\"225V49\"},{\"file\":[{\"fileRefNo\":\"AG/CSD/1\",\"status\":\"Inactive\"}],\"requestNo\":\"225SRV\"},{\"file\":[{\"fileRefNo\":\"AG/CSD/2\",\"status\":\"Active\"}],\"requestNo\":\"225SRV\"}]" ;
JSONArray json = new JSONArray(jsonString);
Map<String, Object> retMap = new HashMap<String, Object>();
for (int i = 0; i < json.length(); i++ ) {
if(json != JSONObject.NULL) {
retMap = toMap(json.getJSONObject(i));
System.out.println(retMap + "retMap");
//{file=[{fileRefNo=AG/CSD/1, status=Active}], requestNo=225V49}retMap
//{file=[{fileRefNo=AG/CSD/1, status=Inactive}], requestNo=225SRV}retMap
//{file=[{fileRefNo=AG/CSD/2, status=Active}], requestNo=225SRV}retMap
}
}
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
Here is my initial JSONArray
[{
"file": [{
"fileRefNo": "AG/CSD/1",
"status": "Active"
}],
"requestNo": "225V49"
}, {
"file": [{
"fileRefNo": "AG/CSD/1",
"status": "Inactive"
}],
"requestNo": "225SRV"
}, {
"file": [{
"fileRefNo": "AG/CSD/2",
"status": "Active"
}],
"requestNo": "225SRV"
}]
Here is my desired outcome
[{
"file": [{
"fileRefNo": "AG/CSD/1",
"status": "Active"
}],
"requestNo": "225V49"
}, {
"file": [{
"fileRefNo": "AG/CSD/1",
"status": "Inactive"
},{
"fileRefNo": "AG/CSD/2",
"status": "Active"
}],
"requestNo": "225SRV"
}]
https://github.com/octomix/josson
Josson josson = Josson.fromJsonString(
"[{" +
" \"file\": [{" +
" \"fileRefNo\": \"AG/CSD/1\"," +
" \"status\": \"Active\"" +
" }]," +
" \"requestNo\": \"225V49\"" +
"}, {" +
" \"file\": [{" +
" \"fileRefNo\": \"AG/CSD/1\"," +
" \"status\": \"Inactive\"" +
" }]," +
" \"requestNo\": \"225SRV\"" +
"}, {" +
" \"file\": [{" +
" \"fileRefNo\": \"AG/CSD/2\"," +
" \"status\": \"Active\"" +
" }]," +
" \"requestNo\": \"225SRV\"" +
"}]");
JsonNode node = josson.getNode("group(requestNo, file).field(file.flatten(1))");
System.out.println(node.toPrettyString());
Output
[ {
"requestNo" : "225V49",
"file" : [ {
"fileRefNo" : "AG/CSD/1",
"status" : "Active"
} ]
}, {
"requestNo" : "225SRV",
"file" : [ {
"fileRefNo" : "AG/CSD/1",
"status" : "Inactive"
}, {
"fileRefNo" : "AG/CSD/2",
"status" : "Active"
} ]
} ]

how to Iterate JsonArray using java 8

I have Json array as below
{ "template": { "data": [{ "name": "customerGroupId", "value": "" }, { "name": "assetIntegrationId", "value": "" }, { "name": "problemCategory", "value": "" }, { "name": "problemSubCategory", "value": "" }, { "name": "resolutionCode", "value": "" }, { "name": "resolutionSubCode", "value": "" }, { "name": "imei", "value": "" }, { "name": "make", "value": "" }, { "name": "model", "value": "" }] } }
I am using following code to get values.
JSONArray jsonArray = jsonObject.getJSONObject("template").getJSONArray("data");
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObjectData = jsonArray.getJSONObject(i);
if ("customerGroupId".equals(jsonObjectData.get("name"))) {
customerBean.setCustomerGroupId(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON customerGroupId " + jsonObjectData.get(VALUE).toString());
} else if ("assetIntegrationId".equals(jsonObjectData.get("name"))) {
customerBean.setAssetIntegrationId(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON assetIntegrationId " + jsonObjectData.get(VALUE).toString());
} else if ("problemCategory".equals(jsonObjectData.get("name"))) {
customerBean.setProblemCategory(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON problemCategory " + jsonObjectData.get(VALUE).toString());
} else if ("problemSubCategory".equals(jsonObjectData.get("name"))) {
customerBean.setProblemSubCategory(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON problemSubCategory " + jsonObjectData.get(VALUE).toString());
} else if ("resolutionCode".equals(jsonObjectData.get("name"))) {
customerBean.setResolutionCode(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON resolutionCode " + jsonObjectData.get(VALUE).toString());
}
As the code has become repetitive,Is there any way in Java 8 or Java to avoid repetition of code.
You can try to use introspector or reflection.
And use name to find property or field.
Introspector:
JSONArray json = new JSONArray();
CustomerBean customerBean = new CustomerBean();
for (int i = json.size() - 1; i >= 0; i--) {
JSONObject data = json.getJSONObject(i);
PropertyDescriptor propDesc = new PropertyDescriptor(data.getString("name"), CustomerBean.class);
Method methodWriter = propDesc.getWriteMethod();
methodWriter.invoke(customerBean, data.getString("value"));
}
Reflection:
JSONArray json = new JSONArray();
CustomerBean customerBean = new CustomerBean();
for (int i = json.size() - 1; i >= 0; i--) {
JSONObject data = json.getJSONObject(i);
Field field = CustomerBean.class.getDeclaredField(data.getString("name"));
field.set(customerBean, data.get("data"));
}

XMLSerializer missing tags

I have a big problem with XMLSerializer... I use JSON lib (net.sf.json) and this is my code:
public static void main(String[] args) throws Exception {
String xmlInputMsg = "<state>\n" +
" <appId>newID</appId>\n" +
" <newDocuments>\n" +
" <nameValues>\n" +
" <name>test1</name>\n" +
" <value>123456</value>\n" +
" </nameValues>\n" +
" <nameValues>\n" +
" <name>test2</name>\n" +
" <value>987654</value>\n" +
" </nameValues>\n" +
" </newDocuments>\n" +
" <oldDocument>\n" +
" <oldAppId>true</oldAppId>\n" +
" <name>App</name>\n" +
" <source>NA</source>\n" +
" </oldDocument>\n" +
"</state>";
String result = null;
XMLSerializer xmlSerializer = new XMLSerializer();
xmlSerializer.setForceTopLevelObject(true);
result = XMLSerializer.class.toGenericString();
System.out.println(result);
}
My current output is:
"state": {
"appId": "newID",
"newDocuments": [
{
"name": "test1",
"value": "123456"
},
{
"name": "test2",
"value": "987654"
}
],
"oldDocument": {
"oldAppId": "true",
"name": "App",
"source": "NA"
}
}}
But I would like have this msg:
{
"state": {
"appId": "newID",
"newDocuments": {
"nameValues": [
{
"name": "test1",
"value": "123456"
},
{
"name": "test2",
"value": "987654"
}
]
},
"oldDocument": {
"oldAppId": "true",
"name": "App",
"source": "NA"
}
}}
Unfortunately now I missing tag nameValues. Could someone help me with this?

Looping through nested JSON array, getting children with same object model

I have a JSON response that looks like the following:
[
{
"id": 5,
"user_id": 1,
"message": "Hello",
"children": [
{
"id": 7,
"user_id": 2,
"message": "Hi",
"children": [
{
"id": 8,
"user_id": 3,
"message": "Hey",
"children": [
]
}
]
}
]
},
{
"id": 6,
"user_id": 4,
"message": "Ahoy",
"children": [
]
}
]
I already have the model created (Message.java). The children can be retrieved by calling getChildren(). The response is saved in a list List<Message> messages.
How can I loop through this JSON array to get the contents of each child until there is no child left? Is this possible without a recursive function?
I Assume you have List messages :
Here is how you can browse through all children with both recursion and iterative way :
List<Message> messages = //you already have that
System.out.println("Using Recusion : ");
for (Message message : messages) {
printMessage(message);
}
System.out.println("Using Iterative : ");
Stack<Message> stack = new Stack<>();
stack.addAll(messages);
while (!stack.empty()) {
Message item = stack.pop();
System.out.println(item.getId() + ":" + item.getUser_id() + ":" + item.getMessage());
for (Message chidren : item.getChildren()) {
stack.push(chidren);
}
}
and here is the printMessage method :
public static void printMessage(Message pmessage) {
System.out.println(pmessage.getId() + ":" + pmessage.getUser_id() + ":" + pmessage.getMessage());
for (Message message : pmessage.getChildren()) {
printMessage(message);
}
}
public void printJsonObject(JSONObject jsonObj) {
for (String keyStr : jsonObj.keySet()) {
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
if (keyvalue instanceof JSONObject)
printJsonObject((JSONObject)keyvalue);
}
}

Categories

Resources