I am trying to build a json string in java but I am a bit confused as how I should go about it. This is what I tried so far.
String jsonString = new JSONObject()
.put("JSON1", "Hello World!")
.put("JSON2", "Hello my World!")
.put("JSON3", new JSONObject()
.put("key1", "value1")).toString();
System.out.println(jsonString);
The output is :
{"JSON2":"Hello my World!","JSON3":{"key1":"value1"},"JSON1":"Hello World!"}
The Json I want is as follows :-
{
"data":{
"nightclub":["abcbc","ahdjdjd","djjdjdd"],
"restaurants":["fjjfjf","kfkfkfk","fjfjjfjf"],
"response":"sucess"
}
}
How should I go about it?
You will need to use JSONArray and JsonArrayBuilder to map these json arrays.
This is the code you need to use:
String jsonString = new JSONObject()
.put("data", new JSONObject()
.put("nightclub", Json.createArrayBuilder()
.add("abcbc")
.add("ahdjdjdj")
.add("djdjdj").build())
.put("restaurants", Json.createArrayBuilder()
.add("abcbc")
.add("ahdjdjdj")
.add("djdjdj").build())
.put("response", "success"))
.toString();
You can use gson lib.
First create pojo object:
public class JsonReponse {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public class Data {
private String reponse;
private List<String> nightclub;
private List<String> restaurants;
public String getReponse() {
return reponse;
}
public void setReponse(String reponse) {
this.reponse = reponse;
}
public List<String> getNightclub() {
return nightclub;
}
public void setNightclub(List<String> nightclub) {
this.nightclub = nightclub;
}
public List<String> getRestaurants() {
return restaurants;
}
public void setRestaurants(List<String> restaurants) {
this.restaurants = restaurants;
}
}
}
and next complite data and generate json:
JsonReponse jsonReponse = new JsonReponse();
JsonReponse.Data data = jsonReponse.new Data();
data.setReponse("sucess");
data.setNightclub(Arrays.asList("abcbc","ahdjdjd","djjdjdd"));
data.setRestaurants(Arrays.asList("fjjfjf","kfkfkfk","fjfjjfjf"));
jsonReponse.setData(data);
Gson gson = new Gson();
System.out.println(gson.toJson(jsonReponse));
Related
I am having a JSON data and I am converting that payload into a map object of nested. But it is overriding according to my logic.
I am having input json like this
{"mapping": {
"EVENT.alertMessage": "input.Message",
"EVENT.id": "input.id",
"EVENT.severity": "Functions.toString(\"P1\")",
"EVENT.eventTime": "input.eventTime",
"EVENT.eventType": "input.alertType",
"EVENT.geocoordinates.location": "Functions.toString(\"\")",
"EVENT.deviceName": "Functions.toString(\"\")",
"EVENT.visualInfo.imageUrl": "input.imageUrl",
"EVENT.deviceId": "input.cameraId",
"EVENT.geocoordinates.longitude": "Functions.toString(\"\")",
"EVENT.visualInfo.videoUrl": "input.videoUrl",
"EVENT.tenantCode": "Functions.toString(\"\")",
"EVENT.MAC": "input.cameraId",
"EVENT.DATE_TIME": "Functions.currentDate(\"yyyy-MM-dd HH:mm:ss\",\"UTC\")",
"EVENT.geocoordinates.latitude": "Functions.toString(\"\")"
}
}
Here from the above input JSON Keys I am iterating and forming map object.
ForEx:
INPUT:
{"mapping": {
"TEST.key1": "a",
"TEST.key2.key3": "b",
}
}
OUTPUT:
{
"TEST":{
"key1":a,
"key2":{
"key3":b
}
}
}
The code that I have written is
JSONObject json=new JSONObject(mappingData).getJSONObject("mapping");
Iterator<String> keys=new JSONObject(mappingData).getJSONObject("mapping").keys();
Map<String,Object> map = new HashMap<>();
while(keys.hasNext()) {
String val = keys.next();
String[] key=val.split("(?<!/)\\.");
Map<String, Object> lastKeyMap = null;
for(int i=0;i<key.length;i++)
{
if(i== 0 && key.length==1){
String outputVal=json.getString(val);
if(outputVal.contains("[]")){
outputVal=outputVal.replace("[]", "[i]");
}
//Matcher m = Pattern.compile("\\.([a-zA-Z0-9]{0,}\\/.[a-zA-Z0-9])|([a-zA-Z0-9]{0,}\\/.[a-zA-Z0-9])")
// .matcher(outputVal);
Matcher m = Pattern.compile("\\.([a-zA-Z0-9]{0,}\\/.[a-zA-Z0-9]{0,})")
.matcher(outputVal);
while (m.find()) {
outputVal=m.replaceAll("[`$1`]").replace("/", "");
}
if(key[i].contains("/"))
{
map.put("`"+key[i].replace("/", "")+"`",outputVal);
}
else{
map.put(key[i],outputVal);
}
}
else if(i== 0 && key.length>1){
if(map.containsKey(key[i])){
lastKeyMap = (Map<String, Object>) map.get(key[i]);
}else{
if(key[i].contains("/"))
{
lastKeyMap = new HashMap<String,Object>();
map.put("`"+key[i].replace("/", "")+"`",lastKeyMap);
}
else{
lastKeyMap = new HashMap<String,Object>();
map.put(key[i],lastKeyMap);
}
}
}else if(i== key.length-1 ){
String outputVal=json.getString(val);
if(outputVal.contains("[]")){
outputVal=outputVal.replace("[]", "[i]");
}
//Matcher m = Pattern.compile("\\.([a-zA-Z0-9]{0,}\\/.[a-zA-Z0-9])|([a-zA-Z0-9]{0,}\\/.[a-zA-Z0-9])")
// .matcher(outputVal);
Matcher m = Pattern.compile("\\.([a-zA-Z0-9]{0,}\\/.[a-zA-Z0-9]{0,})")
.matcher(outputVal);
while (m.find()) {
outputVal=m.replaceAll("[`$1`]").replace("/", "");
}
if(key[i].contains("/"))
{
lastKeyMap.put("`"+key[i].replace("/", "")+"`", outputVal);
}
else{
lastKeyMap.put(key[i], outputVal);
}
}else{
Map<String,Object> objMap = new HashMap<>();
if(key[i].contains("/"))
{
lastKeyMap.put("`"+key[i].replace("/", "")+"`", objMap);
lastKeyMap = objMap;
}
else{
lastKeyMap.put(key[i], objMap);
lastKeyMap = objMap;
}
}
}
}
The output I am getting is :
{EVENT={severity=Functions.toString("P1"), alertMessage=input.alertMessage, id=input.id, eventTime=input.eventTime, visualInfo={videoUrl=input.videoUrl}, eventType=input.alertType, tenantCode=Functions.toString(""), DATE_TIME=Functions.currentDate("yyyy-MM-dd HH:mm:ss","UTC"), geocoordinates={latitude=Functions.toString("")}, deviceName=Functions.toString(""), deviceId=input.cameraId, MAC=input.cameraId}}
But in the result EVENT.geocoordinates.longitude and EVENT.geocoordinates.longitude is skipped as the map is being overridden. Like that EVENT.visualInfo.imageUrl is also overridden by EVENT.visualInfo.videoUrl.So, how can I overcome this one and form a map or json with all the json keys by iterating without veing overriden.
The best approach is to create java class according to json schema:
public class Test {
#SerializedName("mapping")
public Mapping mapping;
static public class Mapping {
#SerializedName("EVENT.alertMessage")
public String alertMessage;
#SerializedName("EVENT.id")
public String id;
#SerializedName("EVENT.severity")
public String severity;
#SerializedName("EVENT.eventTime")
public String eventTime;
#SerializedName("EVENT.eventType")
public String eventType;
#SerializedName("EVENT.geocoordinates.location")
public String location;
#SerializedName("EVENT.deviceName")
public String deviceName;
#SerializedName("EVENT.visualInfo.imageUrl")
public String imageUrl;
#SerializedName("EVENT.deviceId")
public String deviceId;
#SerializedName("EVENT.geocoordinates.longitude")
public String longitude;
#SerializedName("EVENT.visualInfo.videoUrl")
public String videoUrl;
#SerializedName("EVENT.tenantCode")
public String tenantCode;
#SerializedName("EVENT.MAC")
public String mac;
#SerializedName("EVENT.DATE_TIME")
public String dateTime;
#SerializedName("EVENT.geocoordinates.latitude")
public String latitude;
}
}
And then parse it with google gson library
Test test = new Gson().fromJson("jsonString", Test.class);
Working with your own java object is much easier than with JSONObject
My current dependency for gson in gradle file:
implementation("com.google.code.gson:gson:2.8.6")
I am using below code to automate REST API.
Please help me to understand how can I put whole json data for sample data mentioned below as the input has arrays whereas till now I used flat jsons without arrays
Method Dummy()
{
RestAssured.baseURI ="http://mydummyURL";
RequestSpecification request = RestAssured.given();
JSONObject requestParams = new JSONObject();
requestParams.put("id", "THAILAND"); //Issue is with this code
request.header("Content-Type", "application/json");
request.body(requestParams.toJSONString());
Response response = request.post("/EndPoint");
}
where the json body looks like this
{
"tag1": "value1",
"tag2": "value2",
"tag3": {
"tag31": "value31",
"tag32": "value32"
},
"tag4": [{
"domainName": "ABC",
"domainId": "123ABC123",
"domainGUID": "TestMyDomain"
},
{
"domainName": "XYZ",
"domainId": "123XYZ123",
"domainGUID": "TestMyDomain"
}
]
}
ArrayList<JSONObject> array= new ArrayList<JSONObject>();
JSONObject json= new JSONObject();
try {
json.put("key", "value");// your json
} catch (JSONException e) {
e.printStackTrace();
}
array.add(json);
String printjsonarray= array.toString();// pass this into the request
ObjectMapper mapper = new ObjectMapper();
//Create a Java Class for the variables inside array.
JsonArrayData tag4paramVal1 = new JsonArrayData("ABC","123ABC123","TestMyDomain");
JsonArrayData tag4paramVal2 = new JsonArrayData("XYZ","123XYZ123","TestMyDomain");
Object[] tag4ValArray = {tag4paramVal1,tag4paramVal2};
String reqJson = null;
List<String> tag4Data = new ArrayList<String>();
for(Object obj:tag4ValArray){
reqJson = mapper.writeValueAsString(obj);
System.out.println(reqJson);
tag4Data.add(reqJson);
}
System.out.println(tag4Data);
HashMap<String,List<String>> finalReq = new HashMap<String,List<String>>();
finalReq.put("\"tag4\":",tag4Data);
String finalreqString = finalReq.toString();
System.out.println(finalreqString);
finalreqString = finalreqString.replace('=', ' ');
System.out.println(finalreqString);
//Use the above String as a parameter to POST request. You will get your desired JSON array .
//JsonArrayData class code
public class JsonArrayData {
String domainName;
String domainId;
String domainGUID;
public JsonArrayData(String domainName,String domainId,String domainGUID){
this.domainName = domainName;
this.domainId = domainId;
this.domainGUID = domainGUID;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
public String getDomainGUID() {
return domainGUID;
}
public void setDomainGUID(String domainGUID) {
this.domainGUID = domainGUID;
}
}
I have this string:
{"markers":[{"tag":"1","dep":"2"}]}
How to convert it to JSON and get value tag and dep?
you need JSONObject to do this
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET,url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String tag, dep;
JSONArray jArray = response.getJSONArray("markers");
JSONObject msg = jArray.getJSONObject(0);
tag = msg.getString("tag");
dep = msg.getString("dep");
}
}
try
{
JSONObject object = new JSONObject(json_str);
JSONArray array= object.getJSONArray("markers");
for(int i=0;i<array.length();i++)
{
JSONObject obj= array.getJSONObject(i);
String tag= obj.getString("tag");
int dep= obj.getInt("dep");
}
}catch(JSONException e){
}
Hope this helps.
it's good habbit to serialize the json to pojo object ..
here you can use Gson (a google library to serialize/deserialize json to pojo object)
Assuming you are using Android-Studio IDE for android development
Step 1 : add this gson dependency on build.gradle file of module scope
compile 'com.google.code.gson:gson:2.4'
Step 2: create model for json
{"markers":[{"tag":"1","dep":"2"}]}
Markers.java
public class Markers {
/**
* tag : 1
* dep : 2
*/
private List<MarkersEntity> markers;
public void setMarkers(List<MarkersEntity> markers) {
this.markers = markers;
}
public List<MarkersEntity> getMarkers() {
return markers;
}
public static class MarkersEntity {
private String tag;
private String dep;
public void setTag(String tag) {
this.tag = tag;
}
public void setDep(String dep) {
this.dep = dep;
}
public String getTag() {
return tag;
}
public String getDep() {
return dep;
}
}
}
Step 3: serialise json string to pojo object using gson
Gson gson = new Gson();
Markers markers = gson.fromJson(<jsonstring>.toString(), Markers.class);
Step 4: iterate the markers.getMarkersEntity() to get values of tag & dep
for(MarkersEntity data:markers.getMarkersEntity())
{
String tag = data.getTag();
String dep = data.getDep();
Log.d("JSON to Object", tag +"-"+dep);
}
You can use Ion Library for this and parse it as follows:
Ion.with(MainActivity.this).load("url").asJsonObject().setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception arg0, JsonObject arg1) {
// TODO Auto-generated method stub
if(arg0==null)
{
arg1.get("markers").getAsJsonArray();
JsonObject Jobj=arg1.getAsJsonObject();
String tag=Jobj.get("tag").getAsString();
String dep=Jobj.get("dep").getAsString();
}
}
});
Here, you may find your solution. Try it.
try {
//jsonString : {"markers": [{"tag":"1","dep":"2"}]}
JSONObject mainObject = new JSONObject(jsonString);
JSONArray uniArray = mainObject.getJSONArray("markers");
JSONObject subObject = uniArray.getJSONObject(0);
String tag = subObject.getString("tag");
String dep = subObject.getString("dep");
} catch (JSONException e) {
e.printStackTrace();
}
This question already has answers here:
How to parse a dynamic JSON key in a Nested JSON result?
(5 answers)
Closed 7 years ago.
I have been looking for parsing JSON data in java/android. unfortunately, there is no JSON that same as mine. i have JSON data that include weird number, looks like :
{
"formules": [{"1":
{
"formule": "Linear Motion",
"url": "qp1"
},"2":
{
"formule": "Constant Acceleration Motion",
"url": "qp2"
},"3":
{
"formule": "Projectile Motion",
"url": "qp3"
}
}
]
}
Please help me how to parse this in Java/android. Thanks
try this
JSONObject jsonObject = new JSONObject(string);
JSONArray jsonArray = jsonObject.getJSONArray("formules");
JSONObject jsonObject1 = jsonArray.getJSONObject(0);
Now you can access object "1" as
JSONObject json = jsonObject1.getJSONObject("1");
or use iterator to iterate as below
Iterator keys = jsonObject1.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
JSONObject json = jsonObject1.getJSONObject(currentDynamicKey);
}
let me know if it works
For parsing Json in Android, I have found the Gson Library to be helpful
http://mvnrepository.com/artifact/com.google.code.gson/gson/2.3
What it would require is creating a pojo class that represents your object. Might look something like
public class ClassPojo
{
private Formules[] formules;
public Formules[] getFormules ()
{
return formules;
}
public void setFormules (Formules[] formules)
{
this.formules = formules;
}
#Override
public String toString()
{
return "ClassPojo [formules = "+formules+"]";
}
}
public class Formules
{
private Formule 3;
private Forumle 2;
private Formule 1;
}
public class Formule
{
private String formule;
private String url;
public String getFormule ()
{
return formule;
}
public void setFormule (String formule)
{
this.formule = formule;
}
public String getUrl ()
{
return url;
}
public void setUrl (String url)
{
this.url = url;
}
#Override
public String toString()
{
return "ClassPojo [formule = "+formule+", url = "+url+"]";
}
}
then to convert it to and from JSon,you could use
//Convert to JSON
ClassPojo pojo = new ClassPojo();
Gson gson = new Gson();
String json = gson.toJson(pojo);
//COnvert back to Java object
ClassPojo pojo = gson.fromJson(json,ClassPojo.class);
I have a decent amount of experience with REST and JSON, but I'm failing at coming up with a way to read some JSON as a Java object.
The response is here: https://api.kraken.com/0/public/OHLC?pair=XBTCZEUR&interval=60
Notice how one of the names (the relevant data) is dependent on a query parameter. I'm not sure how to create a Java object for Gson to use for deserialization, as one of the variable names can change.
I thought that maybe using a JsonReader to read the response in a streaming fashion might work, but when I do this I get a 403 error response.
Any ideas?
If you don't have exact knowledge regarding what the response will contain, you can always use an implementation of map class to pass on to gson, as I have tried to demonstrate in here :
public class RestResponse {
private boolean success;
private String errorDescription;
private Map<String, Object> data;
private static Gson GSON = new Gson();
private RestResponse()
{
data = new HashMap<String, Object>();
}
public boolean isSuccess() {
return success;
}
private void setSuccess(boolean success) {
this.success = success;
}
public String getErrorDescription() {
return errorDescription;
}
private void setErrorDescription(String errorDescription) {
this.errorDescription = errorDescription;
}
public Object getData(String... nestedKeys)
{
List<String> nestedKeysAsList = Arrays.asList(nestedKeys);
return getData(nestedKeysAsList);
}
public Object getData(List<String> nestedKeys)
{
String firstKey = nestedKeys.get(0);
if(!data.containsKey(firstKey))
throw new IllegalArgumentException("Key not found");
Object mapValue = data.get(firstKey);
if(!(mapValue instanceof Map))
return mapValue;
String finalKey = nestedKeys.get(nestedKeys.size()-1);
if(nestedKeys.size() > 2)
{
for(String nextKey : nestedKeys.subList(1,nestedKeys.size()-1))
{
Map<String,Object> tempMap = (Map)mapValue;
mapValue = tempMap.get(nextKey);
}
}
Map<String,Object> tempMap = (Map)mapValue;
return tempMap.get(finalKey);
}
private Map<String, Object> getData() {
return data;
}
private void setData(Map<String, Object> map){
this.data = map;
}
public static RestResponse createUnsuccessfulResponse(Exception e)
{
return createUnsuccessfulResponse(e.getMessage());
}
public static RestResponse createUnsuccessfulResponse(String reason)
{
RestResponse res = new RestResponse();
res.setSuccess(false);
res.setErrorDescription(reason);
return res;
}
public static RestResponse createSuccessfulResponse(String jsonString)
{
Map<String, Object> jsonToDataMap = GSON.fromJson(jsonString, Map.class);
return createSuccessfulResponseByMap(jsonToDataMap);
}
private static RestResponse createSuccessfulResponseByMap(Map<String, Object> jsonToDataMap)
{
RestResponse res = new RestResponse();
res.setSuccess(true);
res.setErrorDescription("Success");
res.setData(jsonToDataMap);
return res;
}
}
Usage examples can be found over here :
https://github.com/cgunduz/btcenter/blob/master/src/main/java/com/cemgunduz/utils/entity/RestResponse.java