I have a JSON response and I want to store each element in a string. as I am new to JSON, its difficult to find the solution. please suggest me a solution.
the below is my json response.
{
"responseFlag": 1,
"responseMsg": "Successfully retrieved data",
"responseObj": [{
"assets": {
"asset_since": "",
"asset_type": "",
"comments": "",
"estimated_value": "",
"material_status": "SINGLE",
"ownership_of_assets": "",
"pep": "",
"source_of_income": ""
}
},
{
"assets": {
"asset_since": "",
"asset_type": "",
"comments": "",
"estimated_value": "",
"material_status": "SINGLE",
"ownership_of_assets": "",
"pep": "",
"source_of_income": ""
}
}
]
}
I want to store each object elements in an array.
the code I have tried is below.
package mytry;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Mytry {
public static void main(String[] args) {
// TODO code application logic here
String response="{\n" +
" \"responseFlag\": 1,\n" +
" \"responseMsg\": \"Successfully retrieved data\",\n" +
" \"responseObj\": [\n" +
" {\n" +
" \"assets\": {\n" +
" \"asset_since\": \"\",\n" +
" \"asset_type\": \"\",\n" +
" \"comments\": \"\",\n" +
" \"estimated_value\": \"\",\n" +
" \"material_status\": \"SINGLE\",\n" +
" \"ownership_of_assets\": \"\",\n" +
" \"pep\": \"\",\n" +
" \"source_of_income\": \"\"\n" +
" }},\n" +
" {\n" +
" \"assets\": {\n" +
" \"asset_since\": \"\",\n" +
" \"asset_type\": \"\",\n" +
" \"comments\": \"\",\n" +
" \"estimated_value\": \"\",\n" +
" \"material_status\": \"SINGLE\",\n" +
" \"ownership_of_assets\": \"\",\n" +
" \"pep\": \"\",\n" +
" \"source_of_income\": \"\"\n" +
" }}]}";
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(response);
JSONObject jsonObject = (JSONObject) obj;
//System.out.println(jsonObject.toString());
System.out.println("json size=="+jsonObject.size());
System.out.println("hghgfh"+jsonObject.keySet());
Long sflag = (Long) jsonObject.get("responseFlag");
String msg=(String) jsonObject.get("responseMsg");
String resobj=(String) jsonObject.get("responseObj").toString();
//jsonObject.
System.out.println("sflag=="+sflag);
System.out.println("msg=="+msg);
System.out.println("msg=="+resobj);
// JSONArray msg = (JSONArray) jsonObject.get("responseFlag");
// Iterator<String> iterator = msg.iterator();
// while (iterator.hasNext()) {
// System.out.println(iterator.next());
// }
// for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
// String key = (String) iterator.next();
// System.out.println(jsonObject.get(key));
//}
// String asset = (String) jsonObject.get("assets");
// System.out.println("session token"+asset);
//sflag = (Long) jsonObject.get("responseFlag");
//System.out.println("session sflag"+sflag);
} catch (ParseException ex) {
System.out.println(ex);
}
}
}
the response object is
[{
"assets": {
"comments": "",
"asset_since": "",
"material_status": "SINGLE",
"source_of_income": "",
"ownership_of_assets": "",
"asset_type": "",
"pep": "",
"estimated_value": ""
}
}, {
"assets": {
"comments": "",
"asset_since": "",
"material_status": "SINGLE",
"source_of_income": "",
"ownership_of_assets": "",
"asset_type": "",
"pep": "",
"estimated_value": ""
}
}]
I need each asset values to be stored in an array.
Here is a pseudo code. You can fill the missing parts in this code.
String json = "{"responseFlag":1,"responseMsg":"Successfully retrieved data","responseObj":[{"assets":{"asset_since":"","asset_type":"","comments":"","estimated_value":"","material_status":"SINGLE","ownership_of_assets":"","pep":"","source_of_income":""}},{"assets":{"asset_since":"","asset_type":"","comments":"","estimated_value":"","material_status":"SINGLE","ownership_of_assets":"","pep":"","source_of_income":""}}]}";
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("responseObj");
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject arrayJsonObject = jsonArray.getJSONObject(i);
//insert into your list or array
}
If you are using using json-simple-1.1.1 jar. here is the code below:
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(response);
JSONObject jsonObject = (JSONObject) obj;
//System.out.println(jsonObject.toString());
System.out.println("json size==" + jsonObject.size());
System.out.println("hghgfh" + jsonObject.keySet());
JSONArray jsonArray = (JSONArray)jsonObject.get("responseObj");
for(int i=0; i<jsonArray.size(); i++)
{
JSONObject arrayJsonObject = (JSONObject) jsonArray.get(i);
JSONObject assets = (JSONObject) arrayJsonObject.get("assets");
// read the assets to store
}
}catch (Exception e){
}
Related
I am able to update the value of jsonObject by using key name , here the method which I am using
private static JSONObject setValue(JSONObject json, String key, String newValue) throws JSONException {
Iterator<?> keys = json.keys();
while (keys.hasNext()) {
String k = (String) keys.next();
if (key.equals(k)) {
json.put(key, newValue);
}
Object value = json.opt(k);
if (value instanceof JSONObject) {
setValue((JSONObject) value, key, newValue);
}
}
return json;
}
But this is not working in case of JSONArray object , I tried surfing , tried some method but not able to get desire output , an sample request payload:
{
"sactions": [
{
"fund": "REAL",
"amount": {
"value": 130.24,
"curr": "RMB"
},
"type": "TD",
"desc": "TD",
"code": "PROMO",
"id": "deaedd69e3-6707-4b27-940a-39c3b64abdc7"
}
]
}
Looking an recursive method to update value for any given key.
This is what I tried , but did not work
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator<?> iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym))) {
js1.put(key, valueNew);
return js1;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
if (js1.optJSONArray(key) != null) {
JSONArray jArray = js1.getJSONArray(key);
for (int i = 0; i < jArray.length(); i++) {
js1 = jArray.getJSONObject(i);
}
break;
}
}
}
return js1;
}
This is how I am using the method (Ceating request body using lombok and jakson)
ObjectMapper mapper = new ObjectMapper();
String.valueOf(setValue(new JSONObject(mapper.writeValueAsString(transferFund())),
field, " "))
Thanks in advance
You can utilize JsonPath jayway to save your time.
For example:
String jsonInput = "{\n" +
" \"sactions\": [\n" +
" {\n" +
" \"fund\": \"REAL\",\n" +
" \"amount\": {\n" +
" \"value\": 130.24,\n" +
" \"curr\": \"RMB\"\n" +
" },\n" +
" \"type\": \"TD\",\n" +
" \"desc\": \"TD\",\n" +
" \"code\": \"PROMO\",\n" +
" \"id\": \"deaedd69e3-6707-4b27-940a-39c3b64abdc7\"\n" +
" }\n" +
" ]\n" +
"}";
String newJson = JsonPath.parse(jsonInput).set("$..id", "test").jsonString();
System.out.println(newJson);
I want to convert the following JSON using JsonObect and JsonArray but not able to do so.
{
"query": {
"bool": {
"must": [
{
"match": {
"customer.partnerName": "Synapse"
}
},
{
"range": {
"customer.billing.chargeAmount": {
"gte": 1,
"lte": 100
}
}
}
],
"filter": [
{
"match": {
"customer.configId": 15
}
}
]
}
}
}
I have tried using JsonObject but not able to achieve the result.
This is just plain copy/paste of your json string into AndroidStudio, it splits the string automatically and adds escape slashes.. it looks horrible but the syntax you wrote is perfectly ok..
String jsonString = " {\n" +
" \"query\": {\n" +
" \"bool\": {\n" +
" \"must\": [\n" +
" {\"match\": \n" +
" { \"customer.partnerName\": \"Synapse\" }},\n" +
"\n" +
" {\n" +
"\"range\" : \n" +
"{\n" +
" \"customer.billing.chargeAmount\" : {\n" +
" \"gte\" : 1,\n" +
" \"lte\" : 100\n" +
" }\n" +
" }}\n" +
" ],\n" +
" \"filter\": [\n" +
" { \"match\": { \"customer.configId\": 15 }}\n" +
" ]\n" +
" }\n" +
" }\n" +
" }";
// HERE BEAUTIFIED
/*jsonString = "{\"query\":{\"bool\":{\"must\":[{\"match\":{\"customer.partnerName\":\"Synapse\"}},{\"range\":{\"customer.billing.chargeAmount\":{\"gte\":1,\"lte\":100}}}],\"filter\":[{\"match\":{\"customer.configId\":15}}]}}}";
*/
try {
JSONObject object = new JSONObject(jsonString);
// NO ERRORS, OBJECT CREATED IN MY CASE
} catch (JSONException e) {
e.printStackTrace();
}
the second option you have is to create the object and inner objects and arrays programmatically.. like this..
try {
JSONObject jsonObject = new JSONObject();
JSONObject query = new JSONObject();
jsonObject.put("query", query);
JSONObject bool = new JSONObject();
query.put("bool", bool);
JSONArray must = new JSONArray();
bool.put("must", must);
JSONObject matchWrap = new JSONObject();
JSONObject match = new JSONObject();
match.put("customer.partnerName", "Synapse");
matchWrap.put("match", match);
must.put(matchWrap);
JSONObject rangeWrap = new JSONObject();
JSONObject range = new JSONObject();
JSONObject customerBillingChargeAmount = new JSONObject();
customerBillingChargeAmount.put("gte", 1);
customerBillingChargeAmount.put("lte", 100);
range.put("customer.billing.chargeAmount", customerBillingChargeAmount);
rangeWrap.put("range", range);
must.put(rangeWrap);
JSONArray filter = new JSONArray();
bool.put("filter", filter);
JSONObject match2Wrap = new JSONObject();
JSONObject match2 = new JSONObject();
match2.put("customer.configId", 15);
match2Wrap.put("match", match2);
filter.put(match2Wrap);
String jsonString2 = jsonObject.toString();
// HERE THE SAME JSON STRING AS YOUR INPUT
} catch (JSONException e) {
e.printStackTrace();
}
This yields the same rasult as your input string when stripped of whitespaces tabs linefeeds etc..
I think what you're looking for is json parsing. This is done in the following way:
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(jsonData); //Insert json string data
//Do other stuff
<script>
var txt = '{"query": {"bool": {"must": [{"match": { "customer.partnerName": "Synapse" }},{"range" : { "customer.billing.chargeAmount" : { "gte" : 1, "lte" : 100 } }}],"filter": [{ "match": { "customer.configId": 15 }}]}}}'
var obj = JSON.parse(txt);
debugger;
document.getElementById("demo").innerHTML = obj.query;
</script>
Hace you tried to Google gson ?
Here is the repo, also you can find relevant implementations online as well.
https://github.com/google/gson
Try this:-
JSONObject jsonObject = new JSONObject(/*Pass your string value here*/ new JSONTokener(result.toString()).nextValue().toString());
//get 'query' as JSONObject
JSONObject jresponseData = new JSONObject(jsonObject.getString("query"));
//since 'bool' is insode 'query'
JSONObject jresponseData_2 =jresponseData.getString("bool");
JSONArray jsonArray = new JSONArray(jresponseData_2.getString("must"));
And you will get the result in JSONArray
So, I would say you should use JsonPath lib to do that.
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
Example of the usage
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
...
public void handle(...) {
...
DocumentContext jsonContext = JsonPath.parse(responseBody);
JSONArray jsonPathPreviousUrl = jsonContext.read("$..previous")
...
This will parse your json qickly, effectivly.
{
"feed": {
"data": [
{
"created_time": "2017-12-12T01:24:21+0000",
"message": "This picture of my grandson with Santa",
"id": ""
},
{
"created_time": "",
"message": "",
"id": ""
},
{
"created_time": "",
"message": "",
"id": ""
}
],
"paging": {
"previous": "https://facebook/v3.2/{your-user-id}/feed?format=json&limit=3&since=1542820440",
"next": "https://facebook/v3.2/{your-user-id}/feed?format=json&limit=3&until=1542583212&"
}
},
"id": "{your-user-id}"
}
Javadoc for json-path
Baeldung article
}
Using java with selenium
I have captured full json in my code
IN my json there are two nodes "Service1" and "Service2"
My requirement is to fetch the details of "Services1" node -->data node
But i am not able to extract only Service1 with data node details(i do not want "test" node details.
Question: Can you please help me to extract data from Service1-with data node only using java code?I am using selenium with java.I need this for one of the script.
Actual response:
{
"Service1": [
{
"data": {
"status": false,
"type": "A",
"order": 1,
"Version": "v6"
},
"test": {
"ModuleID": "123456",
"BoxID": "a777",
"Url": "https://google.com"
}
},
{
"data": {
"status": true,
"type": "B",
"order": 1,
"Version": "v2"
},
"test": {
"ModuleID": "123456",
"BoxID": "a777",
"Url": "https://google.com"
}
}
],
"Service2": {
"data1": {
"status": false,
"type": "c",
"order": 1,
"Version": "v6"
},
"dashboard": {
"ModuleID": "123456",
"BoxID": "a777",
"Url": "https://google.com"
}
}
}
Expected data :
[
{
"status": false,
"type": "A",
"order": 1,
"Version": "v6"
},
{
"status": true,
"type": "B",
"order": 1,
"Version": "v2"
}
]
Fetching the required data is based on the api response. But in the result of the fetched data you can convert it as you want in java as:
Main theme:
JSONObject response = new JSONObject("json data");//replace json data with your given json data
JSONArray service1 = response.getJSONArray("Service1");
JSONObject firstObjectInService1 = service1.getJSONObject(0);
JSONObject secondObjectInService1 = service1.getJSONObject(1);
JSONObject dataInFirstObject = firstObjectInService1.getJSONObject("data");
JSONObject dataInSecondObject = secondObjectInService1.getJSONObject("data");
Full code snippet:
import org.json.*;
public class JsonParsing {
public static void main(String[] args) {
String jsonData = "{\n" +
"\"Service1\": [\n" +
" {\n" +
" \"data\": {\n" +
" \"status\": false,\n" +
" \"type\": \"A\",\n" +
" \"order\": 1,\n" +
" \"Version\": \"v6\"\n" +
" },\n" +
" \"test\": {\n" +
" \"ModuleID\": \"123456\",\n" +
" \"BoxID\": \"a777\",\n" +
" \"Url\": \"https://google.com\"\n" +
"\n" +
" }\n" +
"\n" +
" },\n" +
" {\n" +
" \"data\": {\n" +
" \"status\": true,\n" +
" \"type\": \"B\",\n" +
" \"order\": 1,\n" +
" \"Version\": \"v2\"\n" +
" },\n" +
" \"test\": {\n" +
" \"ModuleID\": \"123456\",\n" +
" \"BoxID\": \"a777\",\n" +
" \"Url\": \"https://google.com\"\n" +
"\n" +
"\n" +
" }\n" +
" }\n" +
"\n" +
"],\n" +
"\"Service2\": {\n" +
" \"data1\": {\n" +
" \"status\": false,\n" +
" \"type\": \"c\",\n" +
" \"order\": 1,\n" +
" \"Version\": \"v6\"\n" +
" },\n" +
" \"dashboard\": {\n" +
" \"ModuleID\": \"123456\",\n" +
" \"BoxID\": \"a777\",\n" +
" \"Url\": \"https://google.com\"\n" +
"\n" +
" }\n" +
"}\n" +
"}";
System.out.println(jsonData);
try {
JSONObject response = new JSONObject(jsonData);//replace json data with your given json data
JSONArray service1 = response.getJSONArray("Service1");
JSONObject firstObjectInService1 = service1.getJSONObject(0);
JSONObject secondObjectInService1 = service1.getJSONObject(1);
JSONObject dataInFirstObject = firstObjectInService1.getJSONObject("data");
JSONObject dataInSecondObject = secondObjectInService1.getJSONObject("data");
System.out.println(dataInFirstObject);
System.out.println(dataInSecondObject);
} catch (JSONException je) {
//do what you want
}
}
}
so finally in dataInFirstObject we have:
{
"status": false,
"type": "A",
"order": 1,
"Version": "v6"
}
and dataInSecondObject we have:
{
"status": true,
"type": "B",
"order": 1,
"Version": "v2"
}
You can use JSON simple library ,it is library used to read/write/parse data in JSON file.In this example i read data from JSON file not a JSON content directly.
private void findData() {
ArrayList<String> dataArrayList=new ArrayList<>();
try {
JSONParser parser = new JSONParser();
InputStream in = getClass().getResourceAsStream("/json/Services.json");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
Object obj = parser.parse(reader);
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("Service1");
Iterator<JSONObject> iterator = msg.iterator();
while (iterator.hasNext()) {
JSONObject jsonObjectData = iterator.next();
JSONObject dataObject = (JSONObject) jsonObjectData.get("data");
System.out.println(dataObject);
//Extract values
dataObject.values().stream().forEach(value->{
System.out.println(value);
dataArrayList.add(value.toString());
});
}
} catch (IOException | org.json.simple.parser.ParseException ex) {
Logger.getLogger(CorporationRegistrationFormController.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you need read JSON content from your code just replace the reader with your content like this : Object obj = parser.parse("JSON content");
I want to extract jkl object from below JSON string. Also after extraction, I want the backslashes to be removed and extract further with the braces. I followed few questions on StackOverflow but it didn't help much.
{
"abc:def": {
"ghi": {
"jkl": "{\"mno:pqr\":{\"ty\":4,\"\\nsensing_service_name:\\\"Number\\\",\\nsensing_service_id: 20\\n}\\n ]\\n}\"}}",
"st": {
"op": 5,
"org": "q9wr9qrq"
},
"uvw": 1
},
"xyz": false
}
}
I tried below code to display jkl object but it is not working. Please suggest what is wrong in this and how to correct the same
JSONObject json = (JSONObject) JSONSerializer.toJSON(data);
JSONObject aa = json.getJSONObject("abc:def");
JSONObject bb = aa.getJSONObject("ghi");
JSONObject cc = bb.getJSONObject("jkl");
System.out.println(cc);
Hope this will help you:
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
public class TestClass {
public static void main(String[] args) throws Exception {
String jsonString = "{\n" +
" \"abc:def\": {\n" +
" \"ghi\": {\n" +
" \"jkl\": \"{\\\"mno:pqr\\\":{\\\"ty\\\":4,\\\"\\\\nsensing_service_name:\\\\\\\"Number\\\\\\\",\\\\nsensing_service_id: 20\\\\n}\\\\n ]\\\\n}\\\"}}\",\n" +
" \"st\": {\n" +
" \"op\": 5,\n" +
" \"org\": \"q9wr9qrq\"\n" +
" },\n" +
" \"uvw\": 1\n" +
" },\n" +
" \"xyz\": false\n" +
" }\n" +
"} ";
JSONObject jsonObject = new JSONObject(jsonString);
jsonObject = (JSONObject) jsonObject.get("abc:def");
jsonObject = (JSONObject) jsonObject.get("ghi");
String result = jsonObject.getString("jkl");
result = StringUtils.replace(result, "\\n", "");
System.out.println(result.replaceAll("\\\\",""));
}
}
I am new to JSON..Am using HTTPUrlConnections and getting some response in JAVA program.The response data will be like,
{
"data": [
{
"id": 1,
"userId": 1,
"name": "ABC",
"modified": "2014-12-04",
"created": "2014-12-04",
"items": [
{
"email": "abc#gmail.com",
"links": [
{
.
.
.
.
}
]
}
]
}
]
}
From this response am able to get the value of "name" field with the below java code.
JSONArray items = newObj.getJSONArray("data");
for (int it=0 ; it < items.length() ; it++){
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
System.out.println("Name----------"+userName);
}
But my requirement is,I need to get the value of "email" ..How should I code for that..
Any advice..
Thanks in advance..
Chitra
You need to first get the items array and each entry of this array contains JSONObject, from which you can call getString("email") .E.g.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class App
{
public static void main( String[] args ) throws JSONException {
JSONObject newObj = new JSONObject("{" +
"\"data\": [\n" +
" {\n" +
"\"id\": 1,\n" +
" \"userId\": 1,\n" +
" \"name\": \"ABC\",\n" +
" \"modified\": \"2014-12-04\",\n" +
" \"created\": \"2014-12-04\",\n" +
" \"items\": [\n" +
" {\n" +
" \"email\": \"abc#gmail.com\",\n" +
" \"links\": [\n" +
" {\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"\n" +
"}");
JSONArray items = newObj.getJSONArray("data");
for (int it = 0; it < items.length(); it++) {
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
JSONArray item = contactItem.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
String email = item.getJSONObject(i).getString("email");
System.out.println(email);
}
System.out.println("Name----------" + userName);
}
}
}
Output
abc#gmail.com
Name----------ABC
Extending your logic only:
JSONArray items = newObj.getJSONArray("data");
for (int it=0 ; it < items.length() ; it++){
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
System.out.println("Name----------"+userName);
JSONArray itemsArr = contactItem.getJSONArray("items");
for (int item=0 ; item < itemsArr.length() ; item++){
String email = item.getString("email");
System.out.println("Email----------"+email);
}
}
This should work, with few tweaks. I have not actually tested it, just writing freehand here.
You can also use Jackson library from FasterXML. You can convert the JSON String into Java object very easily and then you can traverse using iterations on Collections.
If you look the JSON String it contains items which can be considered as an Array within an Array, so in order to get the value of email all you need to do is to create another JSONArray like:
JSONArray itemsArray = contactItem.getJSONArray("items");
Then you can retrieve the value of email over this Array
Thank you so much for your time and response.
The below code did the magic:
JSONArray responseContactData = responseContact.getJSONArray("data");
for (int i=0; i < responseContactData.length(); i++) {
String emails = contactDataValues.getJSONArray("items").getJSONObject(0).getString("email");
}