Generating a JSON array - java

I need to generate a JSON array object ("MainData") as shown below using Java. Can any one suggest to me how can be this done?
{
"MainData":{
"columnHeaderKeys":null,
"rowHeaders":[
{
"id":0001,
"name":abcd
},
{
"id":0002,
"name":xyz
}
],
"data":[
{
"id":0001,
"rowId":"R1",
"status":PASSED
},
{
"id":0002,
"rowId":"R2",
"status":PASSED
}
]
}
}

Using Google GSON, it's quite simple:
JSONObject result = new JSONObject();
result.put("columnHeadersKeys", JSONObject.NULL);
JSONArray headers = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("id", 1);
obj.put("name", "abcd");
headers.put(obj);
obj = new JSONObject();
obj.put("id", 2);
obj.put("name", "xyz");
headers.put(obj);
result.put("rowHeaders", headers);
JSONArray data = new JSONArray();
obj = new JSONObject();
obj.put("id", 1);
obj.put("rowId", "R1");
obj.put("status", "PASSED");
data.put(obj);
obj = new JSONObject();
obj.put("id", 2);
obj.put("rowId", "R2");
obj.put("status", "PASSED");
data.put(obj);
result.put("data", data);
String output = result.toString();
Note that the entire creation of the object can be chained in one statement - however I find it easier to read when it's split out.

Use the Jackson library.
A sample code from the tutorial:
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> userData = new HashMap<String,Object>();
Map<String,String> nameStruct = new HashMap<String,String>();
nameStruct.put("first", "Joe");
nameStruct.put("last", "Sixpack");
userData.put("name", nameStruct);
userData.put("gender", "MALE");
userData.put("verified", Boolean.FALSE);
userData.put("userImage", "Rm9vYmFyIQ==");
mapper.writeValue(new File("user-modified.json"), userData);

You can do like this It works perfectly for me with this line
Log.i("MainJSON", MainJSON.toString()); I have printed Created JSONObject
try{
JSONObject jo1=new JSONObject();
jo1.put("id",001);
jo1.put("name","abcd");
JSONObject jo2=new JSONObject();
jo2.put("id",002);
jo2.put("name","xyz");
JSONArray jarr1=new JSONArray();
jarr1.put(0, jo1);
jarr1.put(1, jo2);
JSONObject jo3=new JSONObject();
jo3.put("id",0001);
jo3.put("rowId","R1");
jo3.put("status","PASSED");
JSONObject jo4=new JSONObject();
jo4.put("id",0002);
jo4.put("rowId","R2");
jo4.put("status","PASSED");
JSONArray jarr2=new JSONArray();
jarr2.put(0, jo3);
jarr2.put(1, jo4);
JSONObject MainDataObj=new JSONObject();
MainDataObj.put("rowHeaders", jarr1);
MainDataObj.put("data", jarr2);
MainDataObj.put("columnHeaderKeys", "null");
JSONObject MainJSON=new JSONObject();
MainJSON.put("MainData", MainDataObj);
Log.i("MainJSON", MainJSON.toString());
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

Take a look here. You will find many projects that will help you.
I would try JSONObject.java from Crockford's JSON for Java Github repository.
Simple usage :
JSONObject obj = new JSONObject()
.put("MainData", new JSONObject()
.put("columnHeaderKeys", null)
.put("rowHeaders", new JSONArray()
.put(new JSONObject()
.put("id", "001")
.put("name", "abc")
)
.put(new JSONObject()
.put("id", "002")
.put("rowId", "R1")
// ...
)
);
Output string with :
String jsonString = obj.toString();
or write directly to file :
obj.write(new FileWriter(new File("/path/to/destination/file")));

Related

How change type of JSONObject when using javax

I have a StringBuilder:
My code is the following:
String response = sb.toString();
// logger.info("response is '{}' ", response);
JsonObject jsonObject = new JsonObject(response);
JsonObject fileStatuses = jsonObject.getJsonObject("FileStatuses");
JsonArray fileStatus = (JsonArray) fileStatuses.getJsonArray("FileStatus");
for (int i = 0; i < fileStatus.size(); ++i) {
JsonObject rec = fileStatus.getJsonObject(i);
String pathSuffix = rec.getString("pathSuffix");
logger.info(" the pathSuffix value is '{}' ", pathSuffix );
}
I want to use the javax.json.JsonObject and not org.json.JsonObject.
So, the problem is in new JsonObject(response); ==> Cannot instantiate the type JsonObject.
I know that org.json.JSONObject has a constructor that takes a String, but I think not the case when using javax.json.JsonObject.
How can I correct my code to make JsonObject jsonObject = new JsonObject(response) take a String and stay using javax.json.JsonObject class?
According to its API instead of using JsonObject jsonObject = new JsonObject(response); you can instantiate it from your response-String like this:
String response = sb.toString();
StringReader reader = new StringReader(response);
JsonReader jsonReader = Json.createReader(reader);
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();

How to build a JSONObject with a JSONArray?

im kinda new using JSON, and everything was fine until i have to make this JSON format.
"function":"ListarHoteles",
"parameters":[""]
Right now my code:
JSONObject JSONarr = new JSONObject();
JSONArray pam = new JSONArray();
jo.put("function", "ListarHoteles");
pam.add(" ");
JSONObject mainOBJ = new JSONObject();
mainOBJ.put("parameters", pam);
And im receiving:
{"{\"function\":\"ListarHoteles\"}":{},"parameters":[" "]}
Thank you
Is this what you want?
JSONObject jsonObject = new JSONObject();
jsonObject.put("function", "ListarHoteles");
JSONArray arr = new JSONArray();
arr.add("");
jsonObject.put("parameters", arr);
System.out.println(jsonObject.toString(2));
Output:
{
"function":"ListarHoteles",
"parameters":[
""
]
}

How to parse "steps" from the google directions API to java (android)

I'm a complete beginner, especially when is comes to JSON parsing.
I've been using the google directions API
to make a basic navigation app that draws a route from two locations, which is all great. However after trying for hours to parse the "steps" from the API, I still can't make it work.
I've used this example https://github.com/hiepxuan2008/GoogleMapDirectionSimple
to parse the JSON to draw the route.
This is done in the following code. (full code on github "Directionfinder.java")
private void parseJSon(String data) throws JSONException {
if (data == null)
return;
List<Route> routes = new ArrayList<Route>();
JSONObject jsonData = new JSONObject(data);
JSONArray jsonRoutes = jsonData.getJSONArray("routes");
for (int i = 0; i < jsonRoutes.length(); i++) {
JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
Route route = new Route();
JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
JSONObject jsonLeg = jsonLegs.getJSONObject(0);
JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
route.endAddress = jsonLeg.getString("end_address");
route.startAddress = jsonLeg.getString("start_address");
route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
route.points = decodePolyLine(overview_polylineJson.getString("points"));
routes.add(route);
}
listener.onDirectionFinderSuccess(routes);
}
Heres how the JSON typically looks. http://pastebin.com/czYkBWWU
I need to parse "maneuver", "start_location", "distance", "start_location and the position from every step of a given route.
It seems fairly easy to parse this, but I just can't figure out how.
Any help will be greatly appreciated!
Here is full code. I Run it in my Device and get Successfull result. If you face problem then let me know.
try {
List<Route> routes=new ArrayList<Route>();
JSONObject mainJSON=new JSONObject(jsonJ);
JSONArray jarray1=mainJSON.getJSONArray("routes");
JSONObject jobj1=jarray1.getJSONObject(0);
JSONArray jarray2=jobj1.getJSONArray("legs");
JSONObject jobj2=jarray2.getJSONObject(0);
JSONArray stepArray=jobj2.getJSONArray("steps");
for (int i=0;i<stepArray.length();i++){
Route route=new Route();
JSONObject jobj5=stepArray.getJSONObject(i);
JSONObject disOBJ=jobj5.getJSONObject("distance");
JSONObject durOBJ=jobj5.getJSONObject("duration");
JSONObject endOBJ=jobj5.getJSONObject("end_location");
JSONObject polOBJ=jobj5.getJSONObject("polyline");
JSONObject startOBJ=jobj5.getJSONObject("start_location");
route.startAddress=jobj2.getString("start_address");
route.endAddress=jobj2.getString("end_address");
if (jobj5.has("maneuver")){
route.maneuver=new Maneuver(jobj5.getString("maneuver"));
}
route.distance=new Distance(disOBJ.getString("text"),disOBJ.getString("value"));
route.duration=new Duration(durOBJ.getString("text"),durOBJ.getString("value"));
route.startLocation=new LatLng(startOBJ.getDouble("lat"),startOBJ.getDouble("lng"));
route.endLocation=new LatLng(endOBJ.getDouble("lat"),endOBJ.getDouble("lng"));
route.points=decodePoluLine(polOBJ.getString("points"));
routes.add(route);
}
} catch (JSONException e) {
e.printStackTrace();
}

Http PUT in body body: Bad request error, can't parse API token

I've got a big trouble parsing and sending request.
In body of request I have to send a token that I've already got successfully while authetification.
Here's a doc:
PUT /api/ver1/orders {"token" : String, "order" : Object}
And here's how I parsing and getting JSONObject:
JSONObject jsonObject = new JSONObject();
JSONObject params = new JSONObject();
params.put(ICConst.ORDER_TYPE, 1);
params.put(ICConst.PAYMENT, 2);
params.put(ICConst.ORDER_NAME, ICApplication.currentOrder .getOrderName());
params.put(ICConst.ORDER_DESCRIPTION, ICApplication.currentOrder .getOrderDescription());
JSONObject addressFrom = new JSONObject();
addressFrom.put(ICConst.CITY_FROM, ICApplication.currentOrder .getCityFrom());
addressFrom.put(ICConst.ADDRESS_FROM, ICApplication.currentOrder .getAddressFrom());
params.put(ICConst.FROM, addressFrom);
JSONObject periodFrom = new JSONObject();
periodFrom.put(ICConst.DATE_FROM, ICApplication.currentOrder .getDateFrom());
periodFrom.put(ICConst.TIME_FROM_START, ICApplication.currentOrder .getTimeFromStart());
periodFrom.put(ICConst.TIME_FROM_TILL, ICApplication.currentOrder .getTimeFromTill());
params.put(ICConst.FROM_PERIOD, periodFrom);
JSONObject addressTo = new JSONObject();
addressTo.put(ICConst.CITY_TO, ICApplication.currentOrder .getCityTo());
addressTo.put(ICConst.ADDRESS_TO, ICApplication.currentOrder .getAddressTo());
params.put(ICConst.TO, addressTo);
JSONObject periodTo = new JSONObject();
periodTo.put(ICConst.DATE_TO, ICApplication.currentOrder .getDateTo());
periodTo.put(ICConst.TIME_TO_START, ICApplication.currentOrder .getTimeToStart());
periodTo.put(ICConst.TIME_TO_TILL, ICApplication.currentOrder .getTimeToTill());
params.put(ICConst.TO_PERIOD, periodTo);
JSONObject sender = new JSONObject();
JSONArray senderPhone = new JSONArray();
sender.put(ICConst.SENDER_NAME, ICApplication.currentOrder .getSenderName());
senderPhone.put(0, ICApplication.currentOrder .getSenderPhone());
sender.put(ICConst.SENDER_PHONE, senderPhone);
params.put(ICConst.SENDER, sender);
JSONObject recipient = new JSONObject();
JSONArray recipientPhone = new JSONArray();
recipient.put(ICConst.RECIPIENT_NAME, ICApplication.currentOrder .getRecipientName());
recipientPhone.put(0, ICApplication.currentOrder .getRecipientPhone());
recipient.put(ICConst.RECIPIENT_PHONE, recipientPhone);
params.put(ICConst.RECIPIENT, recipient);
JSONObject receiver = new JSONObject();
receiver.put(ICConst.RECEIVED_NAME, ICApplication.currentOrder .getReceiverComment());
receiver.put(ICConst.RECEIVED_COMMENT, ICApplication.currentOrder .getReceiverComment());
params.put(ICConst.RECEIVED_BY, receiver);
params.put(ICConst.CARGO, getCargo());
jsonObject.put("order", params);
jsonObject.put("token", ICApplication.currentProfile.getToken());
And here's Httpput request
HttpPut httpPut = new HttpPut(getAbsoluteUrl(url));
httpPut.setHeader(HTTP.CONTENT_TYPE,
"application/x-www-form-urlencoded");
String str = String.valueOf(jsonObject);
StringEntity entity = new StringEntity(str, "UTF-8");
entity.setContentType("application/json");
entity.setContentType("application/x-www-form-urlencoded");
httpPut.setEntity(entity);
HttpResponse response = httpclient.execute(httpPut);
String request = inputStreamToString(response.getEntity().getContent());
Log.v("requestStringEntity", entity + "!");
Log.v("request", request + "!");
Another variant is while I'm using com.loopj.android.http.AsyncHttpClient.
I don't another get, patch and post requests and everything was successfully working except PUT.
Here's the code I've got:
public static void put(Context context, String url, JSONObject jsonObject, AsyncHttpResponseHandler handler) {
StringEntity entity = null;
try {
entity = new StringEntity(jsonObject.toString());
entity.setContentEncoding("UTF-8");
entity.setContentType("application/x-www-form-urlencoded");
} catch (UnsupportedEncodingException _e) {
_e.printStackTrace();
}
client.setURLEncodingEnabled(true);
client.put(context, getAbsoluteUrl(url), entity, "application/json", handler);
}
here's entuty/jsonObject String:
{"token":"b695911b-2973-11e6-acac-06b720391567","order":{"order_type":"1","payment_type":"2","name":"Какой-то
груз","cost":"350","description":"","from":{"latitude":"55.15919993700593","longitude":"65.15919993700593"},"fromPeriod":{"date":"1464944049","from":"15","to":"18"},"to":{"city":"Челябинск","address":"Ленина,
3,
3"},"toPeriod":{"date":"1464944075","from":"15","to":"18:30"},"sender":{"name":"Попов","comment":"Попов","phone":["+70000009111"]},"recipient":{"name":"Иванов
Иван Иваныч","comment":"Иванов Иван
Иваныч","phone":["70000009112"]},"cargo":[{"name":"wwww","description":"wwww","size":{"height":"2","width":"3","length":"4"},"loaders_count":"1","does_need_packaging":false}]}}
I'm not a professional in Rest and httprequest so I've got no idea what the problem is and still have got an exception in the first put method:
{"name":"Bad Request","message":"No API token
found","code":0,"status":400,"type":"yii\web\HttpException"}
Please if anyone has an idea help me!
Try this, instead of
String str = String.valueOf(params);
I think it should be
String str = String.valueOf(jsonObject);
Because you are adding your token to jsonObject and not params.

How do you store arrays into a JSON object?

I have a the following objects:
server: a string
products: will be arrays within the server
productProperties: will be an array within a product
Is the following a correct way to store the value in a JSON format?
JSONOBJECT jmap = new JSONOBJECT();
jsonArray jproduct = new jsonArray ();
jsonArray jproductsProperty1 = new jsonArray ();
jproductsProperty1 .put("P1");
jproductsProperty1 .put("P2");
jsonArray jproductsProperty2 = new jsonArray ();
jproductsProperty2 .put("Q1");
jproductsProperty2 .put("Q2");
jproduct.put(jproductsProperty1);
jproduct.put(jproductsProperty2);
jmap.put(server,jproduct);
out.print(jmap.toString());
first argument its just a key and second its your object could be a collection like a array
JSONOBJECT jmap = new JSONOBJECT();
jsonArray jproductsProperty1 = new jsonArray ();
jproductsProperty1.put("P1");
jproductsProperty1.put("P2");
jsonArray jproductsProperty2 = new jsonArray ();
jproductsProperty2.put("Q1");
jproductsProperty2.put("Q2");
jmap.put("jproductsProperty1", jproductsProperty1 );
jmap.put("jproductsProperty2", jproductsProperty2 );
okay i think i need to use two maps here .....like this
JSONObject jmap1 = new JSONObject();
JSONObject jmap2 = new JSONObject();
JSONArray jproduct = new JSONArray();
JSONArray jproductsProperty1 = new JSONArray();
jproductsProperty1 .put("P1");
jproductsProperty1 .put("P2");
JSONArray jproductsProperty2 = new JSONArray();
jproductsProperty2 .put("Q1");
jproductsProperty2 .put("Q2");
jproduct.put(jproductsProperty1);
jproduct.put(jproductsProperty2);
jmap2.put("jproductsProperty1", jproductsProperty1 );
jmap2.put("jproductsProperty2", jproductsProperty2 );
jmap1.put("A",jmap2);
System.out.println(jmap1);

Categories