I'm trying to generate a 2d JSON array using JSON object in Java. I'm trying to generate the following JSON.
Java Code..
JSONObject root = new JSONObject();
JSONObject c0 = new JSONObject();
JSONObject c1 = new JSONObject();
JSONObject attachment = new JSONObject();
JSONObject payload = new JSONObject();
JSONObject buttons = new JSONObject();
root.put("recipient", c0);
root.put("message", c1);
c0.put("id", userId);
c1.put("message", attachment);
attachment.put("type", "template");
attachment.put("payload", payload);
payload.put("template_type", "button");
payload.put("text", "What do you want to do next");
payload.put("buttons", buttons);
buttons.put("type", "web_url");
buttons.put("url", "https://google.com");
buttons.put("title", "show website");
buttons.put("type", "postback");
buttons.put("title", "Hi There");
buttons.put("payload", "sample payload");
Expected JSON Output..
{
"recipient":{
"id":"USER_ID"
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"What do you want to do next?",
"buttons":[
{
"type":"web_url",
"url":"https://google.com",
"title":"Show Website"
},
{
"type":"postback",
"title":"Start Chatting",
"payload":"Sample_PAYLOAD"
}
]
}
}
}
}
Current Output..
{
"recipient":{"
id":"988459377921053"
},
"message":{
"message":{"
payload":{
"buttons":{
"payload":"sample payload",
"type":"postback",
"title":"Hi There",
"url":"https://google.com"
},
"template_type":"button",
"text":"What do you want to do next"},
"type":"template"
}
}
}
I'm creating nested Json objects and adding them from the outer level to the inner level still the output JSON is not as expected. Can't understand where I'm going wrong.
Edit 1:
Tried changes mentioned by user #user1802604 but the JSON being generated is of the following format..
{
"recipient":{
"id":"988459377921053"
},
"message":{
"attachment":{
"payload":{
"buttons":[
{
"payload":"sample payload",
"type":"postback",
"title":"Hi There",
"url":"https://google.com"
},
{
"payload":"sample payload",
"type":"postback",
"title":"Hi There",
"url":"https://google.com"
}
],
"template_type":"button",
"text":"What do you want to do next"
},
"type":"template"
}
}
}
The API to which I'm sending the JSON is returning response code 400 with message "Bad Request". Is there a way to preserve the order of elements??
I think most of your codes are right. Only two errors need to be fixed.
Note that I'm not sure what library you're using for representing json, so the following codes may not fully correct. I assume that you're using org.json.
c1.put("message", attachment); should be c1.put("attachment", attachment);.
JSONObject buttons = new JSONObject(); should be created as JSONArray buttons = new JSONArray();. So you also have to create another json object for storing type, title, and url.
JSONArray buttons = new JSONArray();
JSONObject button1 = new JSONObject();
button1.put("type", "web_url");
button1.put("url", "https://google.com");
button1.put("title", "show website");
buttons.put(button1);
JSONObject button2 = new JSONObject();
button2.put("payload", "postback");
button2.put("url", "Sample_PAYLOAD");
button2.put("title", "Start Chatting");
buttons.put(button2);
This code is settings value of a JSONObject
buttons.put("type", "web_url");
buttons.put("url", "https://google.com");
buttons.put("title", "show website");
buttons.put("type", "postback");
buttons.put("title", "Hi There");
buttons.put("payload", "sample payload");
Since there is twice each key, you override the first value.
What you want is to add a JSONObject instance into a JSONArray buttons.
JSONArray arrayButton= new JSONArray();
JSONObject button.put("type", "web_url");
button.put("url", "https://google.com");
button.put("title", "show website");
arrayButton.put(button);
button.put("type", "postback");
button.put("title", "Hi There");
button.put("payload", "sample payload");
arrayButton.put(button);
To add each object into an array. Then simply add the array you have build.
Related
I can't seem to get the selection of elements in the array right. Or the syntax swears or something else. Here is what I am trying
{
"info": "info",
"user":[{
0:
"info":{
"name": "user 1"
}
}]
}
Here is my code and what i am trying to do
JSONObject jsonObject = new JSONObject(json_string);
System.out.println(jsonObject.getJSONArray("user").getJSONArray(0).getJSONArray("info").getString("name"));
And I don't get anything. Who can tell me how to do it right
Thanks everyone. I figured out how to do it here is the code)
JSONObject obj = new JSONObject(json_string);
JSONArray userArray = obj.getJSONArray("user");
JSONObject userInfo = userArray.getJSONObject(0).getJSONObject("info");
String reciver = userInfo.getString("name");
I am trying to update a JSON file with input from an HTTP GET request. I so far have the following below but it is returning an org.json.simple.JSONObject cannot be cast to org.json.JSONObject. I have tried numerous methods with this but I am hitting the same hurdle and going round in circles. Please help me.
The goal after seeing the revised JSON data outputted to system is to write it back to file.
HTTP GET RESPONSE FORMAT:
{
array: [
"data1" : "data 1",
"data2" : "data 2",
"data3" : "data 3",
"data4" : "data 4",
"data5" : "data 5",
]
}
EXISTING JSON FILE (please note no array):
{
"data5" : "data 5",
"dataA" : "data A",
"dataB" : "data B",
"dataC" : "data C",
"dataD" : "data D",
}
HTTP GET CODE:
#Component
public class ServiceConnector {
private final HttpClient client;
public ServiceConnector() {
client = HttpClientBuilder.create().build();
}
public String get(String url, String acceptHeader, Optional<String> bearerToken) throws UnauthorizedException {
HttpGet request = new HttpGet(url);
request.addHeader("Accept", acceptHeader);
if (bearerToken.isPresent()) {
request.addHeader("Authorization", "Bearer " + bearerToken.get());
}
try {
HttpResponse response = client.execute(request);
//new code
String data = EntityUtils.toString(response.getEntity());
JSONObject root = new JSONObject(data);
JSONArray results = root.getJSONArray("results");
for(int i = 0; i < results.length(); i++) {
JSONObject jsonResult = results.getJSONObject(i);
OBLI Result = new OBLI();
String data1 = jsonResult.getString("data1");
String data2 = jsonResult.getString("data2");
String data3 = jsonResult.getString("data3");
String data4 = jsonResult.getString("data4");
String data5 = jsonResult.getString("data5");
try {
FileReader reader = new FileReader("/root/Desktop/data.json");
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(reader);
System.out.println(jsonObject);
JSONObject dataObj = (JSONObject) jsonObject.get("data5");
System.out.println(periodObj);
dataObj.put("data5",data5);
System.out.println(jsonObject);
}
catch (IOException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
e.printStackTrace();
}
}
//end of new code
if (response.getStatusLine().getStatusCode() == 401) {
throw new UnauthorizedException();
}
return "something else later";
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
I think the problem with "HTTP GET RESPONSE FORMAT".
maybe right JsonArray format is:-
{
"array": [{
"data1" : "data 1",
"data2" : "data 2",
"data3" : "data 3",
"data4" : "data 4",
"data5" : "data 5"
}]
and then you can change
JSONArray results = root.getJSONArray("results"); to JSONArray results = root.getJSONArray("array");
and then use for-each loop for get one by one Object With help of DTOs.
}
So, you can convert jsonArray to JsonObject.
The answer to this question was that org.json and org.json.simple did not create JSONObjects that were interchangeable.
I used Jackson library and ObjectMapper, JsonNode, and ObjectNode to update the file - ultimately removing the org.json.simple library altogether.
I have to make a file in JSON format which must look like the following:
xyz.json
[
{
"imagelist": "/oracle/public/oel6",
"label": "test_higgs",
"shape": "small",
"name" : "/Compute-computecli1/computeadmin/",
"networking" : {
"eth0" : {
"ipnetwork" : "/Compute-computecli1/computeadmin/ipnet"
}
}
}
]
The array should be added in the JSON file without {}, and these curly brackets have to come inside the JSON array.
The code for
{
instances:[
{
"imagelist": "/oracle/public/oel6",
"label": "test_higgs",
"shape": "small",
"name" : "/Compute-computecli1/computeadmin/",
"networking" : {
"eth0" : {
"ipnetwork" : "/Compute-computecli1/computeadmin/ipnet"
}
}
}
]
}
is:
This code adds json array as a value to "instance" key, but I want to add json array without json key.
JsonObject ipnetwork = new JsonObject();
ipnetwork.addProperty("ipnetwork", ipNetworkName);
JsonObject interface_type = new JsonObject();
interface_type.add("eth0", ipnetwork);
JsonObject instance = new JsonObject();
instance.addProperty(imageListCmdText, "/oracle/public/oel6");
instance.addProperty("label","test_higgs");
instance.addProperty("shape","small");
instance.addProperty("name","/"+customerName);
instance.add("networking",interface_type);
JsonArray instances = new JsonArray();
instances.add(instance);
JsonObject launch_plan = new JsonObject();
launch_plan.add("instances", instances);
Please tell how does this code has to be changed in order to get the output asked above.
JsonObject launch_plan = new JsonObject();
launch_plan.add("instances", instances);
These two lines create the JSON object with curly braces. You don't need them, you can just remove them and use instances, which doesn't have curly braces as it's a json array and not a json object.
JsonObject ipnetwork = new JsonObject();
ipnetwork.addProperty("ipnetwork", ipNetworkName);
JsonObject interface_type = new JsonObject();
interface_type.add("eth0", ipnetwork);
JsonObject instance = new JsonObject();
instance.addProperty(imageListCmdText, "/oracle/public/oel6");
instance.addProperty("label","test_higgs");
instance.addProperty("shape","small");
instance.addProperty("name","/"+customerName);
instance.add("networking",interface_type);
JsonArray instances = new JsonArray();
instances.add(instance);
// not needed
//JsonObject launch_plan = new JsonObject();
//launch_plan.add("instances", instances);
Is there an API/tool available for extracting specific attributes(json subset) of a json in java, similar to apache-commons beanutils copy?
For example I have the following JSON
{
"fixed":[
{
"b":"some value",
"c":"some value",
"d":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"c":"value",
"d":"value",
"e":"value",
"f":"value"
}
]
}
I would like to have the following json
{
"fixed":[
{
"b":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"e":"value",
"f":"value"
}
]
}
I came up the following method, but not sure if its the right approach
public JSONObject parseJSON(JSONObject data,List<String> subset){
JSONArray fixedArray = (JSONArray) data.get("fixed");
JSONObject resObj = new JSONObject();
JSONArray resArray = new JSONArray();
for(int i=0;i<fixedArray.size();i++){
JSONObject element = (JSONObject) fixedArray.get(i);
JSONObject resElement = new JSONObject();
for(String s:subset){
resElement.put(s, element.get(s));
}
resArray.add(resElement);
}
return resObj.put("fixed", resArray);
}
I had a look at this SO question, but wasn't helpful for this topic.
https://docs.oracle.com/javase/tutorial/jaxb/intro/arch.html you can also create you own pojo class from JAXB ,if you want.
Original Question: Resolved
I'm producing Json from the controller using JsonObject/JsonArray:
JSONObject headers = new JSONObject();
headers.put("ID", "");
headers.put("Organization Name", "");
headers.put("Submission Date", "");
headers.put("Status", "");
JSONObject organizationsHJ = new JSONObject();
organizationsHJ.put("headers", headers);
array.add(organizationsHJ );
This produces JSON as:
"headers":{"Status":"","Submission Date":"","Organization Name":"","ID":""}
Instead I need to get the output as:
"headers":[ "ID", "Organization Name", "Submission Date", "Status" ]
Is that possible? Please advise. Please note I can have the JSON as a javascript variable as well if that's easier?
EDIT:
I need one more simple change in the JSON output. Here is my code:
JSONObject notifications = new JSONObject();
notifications.put("id", "1");
notifications.put("description", "Notification 1");
notifications.put("createdTimestamp", "2015-05-12T18:15:28.237Z");
notifications.put("startTimestamp", "2015-05-25T18:30:28.237Z");
notifications.put("endTimestamp", "2015-06-13T12:30:30.237Z");
notifications.put("active", "true");
This generates JSON output as:
{"data":{"id":"1","createdTimestamp":"2015-05-12T18:15:28.237Z","description":"Notification 1","startTimestamp":"2015-05-25T18:30:28.237Z","active":"true","createdId":"251","endTimestamp":"2015-06-13T12:30:30.237Z"}}
Instead I want it to generate as:
{"data":["id":"1","createdTimestamp":"2015-05-12T18:15:28.237Z","description":"Notification 1","startTimestamp":"2015-05-25T18:30:28.237Z","active":"true","createdId":"251","endTimestamp":"2015-06-13T12:30:30.237Z"]}
headers should be a JSONArray, not JSONObject. An object is a set of name-to-value mappings, an array is a linear collection.
JSONArray headers = new JSONObject();
headers.add("ID");
headers.add("Organization Name");
headers.add("Submission Date");
headers.add("Status");
JSONObject organizationsHJ = new JSONObject();
organizationsHJ.put("headers", headers);
array.add(organizationsHJ );
organizationsHJ.put("headers", headers.keySet());