Giving Name (Heading) to Objects in JsonArray - java

I want to send following data to server. It contains JsonArray of JsonObjects as shown below.
{
"users":[
{"user-1":{
"Name":"Amit",
"Age":"32",
"Gender":"male",
"Hobby":"Cricket"
}
"user-2":{
"Name":"Subodh",
"Age":"30",
"Gender":"male",
"Hobby":"Chess"
}
"user-3":{
"Name":"Mala",
"Age":"27",
"Gender":"female",
"Hobby":"Singing"
}
}
]
}
This is how I wrote json code for the same.
JSONObject userObject = new JSONObject();
JSONArray userArray = new JSONArray();
JSONObject user1 = new JSONObject();
try {
user1.put("Name", "Amit");
user1.put("Age", "32");
user1.put("Gender", "Male");
user1.put("Hobby", "Cricket");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject user2 = new JSONObject();
try {
user2.put("Name", "Subodh");
user2.put("Age", "30");
user2.put("Gender", "Male");
user2.put("Hobby", "Chess");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject user3 = new JSONObject();
try {
user3.put("Name", "Mala");
user3.put("Age", "27");
user3.put("Gender", "Female");
user3.put("Hobby", "Singing");
} catch (JSONException e) {
e.printStackTrace();
}
userArray.put(user1);
userArray.put(user2);
userArray.put(user3);
try {
userObject.put("user", userArray);
} catch (JSONException e) {
e.printStackTrace();
}
However I am not able to figure out how to give name to Objects (user-1, user-2 etc.) in the JsonArray. Can someone help to do that. I want to give Heading to each JsonObject in the JsonArray.

Your JSON is invalid.
Elements in JSON arrays don't have keys ("headings", as you call them). Only values in JSON objects have keys.
So, this is wrong:
{
"users": [
"user-1": {
"Name": "Amit",
"Age": "32",
"Gender": "male",
"Hobby": "Cricket"
}
]
}
While this is correct:
{
"users": {
"user-1": {
"Name": "Amit",
"Age": "32",
"Gender": "male",
"Hobby": "Cricket"
}
}
}
To get the correct JSON, simply use a JSONObject instead of a JSONArray:
JSONObject resultObject = new JSONObject();
JSONObject usersObject = new JSONObject();
JSONObject user1 = new JSONObject();
user1.put("Name", "Amit");
user1.put("Age", "32");
user1.put("Gender", "Male");
user1.put("Hobby", "Cricket");
usersObject.put("user-1", user1);
// repeat for user 2, 3, 4, ...
resultObject.put("users", usersObject);

Write the JSON object name like below code in every JSONObject creation :-
JSONObject jsonobj = new JSONObject("user1 ");
try {
jsonobj.put("Name", "Amit");
jsonobj.put("Age", "32");
jsonobj.put("Gender", "Male");
jsonobj.put("Hobby", "Cricket");
} catch (JSONException e) {
e.printStackTrace();
}

Related

How to create a JSONObject for nested json

I am unable to create a json object for nested json.
I can create json objects for basic json.
I am unable to add further fields.
final JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
} catch (JSONException e) {
e.printStackTrace();
}
Here is my json:
{
"name": "string",
"description": "string",
"candidates": [
"string"
],
"ballotVisibility": "string",
"voterListVisibility": true,
"startingDate": "2019-07-05T20:09:23.311Z",
"endingDate": "2019-07-05T20:09:23.311Z",
"isInvite": true,
"isRealTime": true,
"votingAlgo": "string",
"noVacancies": 0,
"ballot": [
{
"voteBallot": "string",
"voterEmail": "string"
}
]
}
You just need to create a new JSONObject then append it to the parent object with its new name. An example is shown below appending the ballot:
JSONObject jsonObject = new JSONObject();
JSONObject ballot = new JSONObject();
ballot.put("voteBallot","string");
ballot.put("voterEmail","string");
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
jsonObject.put("ballot", ballot); //Append the other JSONObject to the parent one
System.out.println(jsonObject.toString());
Output(with some formatting):
{
"ballot":
{
"voteBallot":"string",
"voterEmail":"string"
},
"name":"new name",
"description":"new election"
}
You can also use JSONArray instead and append it in the same manner.
Try this:
final JSONObject jsonObject = new JSONObject();
Map<String, String> map = new HashMap<>();
map.put("voteBallot", "string");
map.put("voterEmail", "string");
try {
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
jsonObject.put("candidates", new String[] {"new String"});
jsonObject.put("ballotVisibility", "string");
jsonObject.put("voterListVisibility", true);
jsonObject.put("startingDate", LocalDateTime.now().atZone(ZoneOffset.UTC));
jsonObject.put("ballot", new Map[]{map});
System.out.println("jsonObject = " + jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
it's not all the fields but it's all the different types hope it helps.
Output:
{
"ballot":[
{
"voteBallot":"string",
"voterEmail":"string"
}
],
"candidates":[
"new String"
],
"ballotVisibility":"string",
"name":"new name",
"voterListVisibility":true,
"description":"new election",
"startingDate":"2019-07-05T22:34:58.750Z"
}

Unable to extract jsonarray from jsonobject

I have been battling with response from server using retrofit.
I have this json response from server
{
"success": true,
"message": "Your Requests",
"data": {
"requests": [
{
"_id": "5d163a5ed2399f8be6d8d867",
"created": "2019-06-28T16:03:42.463Z",
"pickupCoordinates": [
8.0099,
6.0909
],
"destinationCoordinates": [
9.088788,
3.099403
],
"customerName": "Seun Akinbode",
"pickupAddress": "Lekki",
"destinationAddress": "Ajah",
"accessCode": "3334",
"busPlate": "DD222RR",
"flaName": "Simi",
"flaEmail": "awele#kobo360.com",
"__v": 0
} ]
}
I use below class to parse the json but unfortunately, it couldn't extract the array requests into jsonArray
public ArrayList<RequestModel> getData(String response)
{
Log.d("responseData :", response);
ArrayList<RequestModel> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("data");
Log.d("The main Array :", array.toString());
RequestModel data;
for(int i = 0;i<array.length();i++)
{
data = new RequestModel();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requests");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
data.setAccessCode(reqObj.getString("accessCode"));
Log.d("Accessecode :", reqObj.getString("accessCode"));
data.setCustomerName(reqObj.getString("customerName"));
Log.d("customerName :", reqObj.getString("customerName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
Logcat is printing the JSONObject but it says at ... data of type org.json.JSONObject cannot be converted to JSONArray
You are trying to extract an array from the data field, while the response contains an object. Perhaps you meant to get the object data, then the array requests from within it.
This could be the problem:
JSONArray array = mainObj.getJSONArray("data");
data is an object as seen in the response, not an array.

Nested JSON response dynamically in java

I need to create a json response like the one below. I tried with some code but couldn't able to get what i need. Need help in java code to create nested array to group the food items according to the categories along with the category details like in below json
{
"menu": {
"items": [{
"id": 1,
"code": "hot1_sub1_mnu",
"name": "Mutton",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Mutton Pepper Fry",
"price": "100"
}, {
"id": "02",
"name": "Mutton Curry",
"price": "100"
}]
},
{
"id": "2",
"code": "hot1_sub2_mnu",
"name": "Sea Food",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Fish Fry",
"price": "150"
}]
},
{
"id": "3",
"code": "hot1_sub3_mnu",
"name": "Noodles",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Chicken Noodles",
"price": "70"
}, {
"id": "02",
"name": "Egg Noodles",
"price": "60"
}]
}
]
}
}
What i tried so far is i can able to only create a response in one single array
#Path("/items")
public class HotelsMenu {
#GET
#Path("/getitems")
#Produces(MediaType.APPLICATION_JSON)
public String doLogin(#QueryParam("hotelcode") String hotelcode) {
JSONObject response = new JSONObject();
JSONArray hotelDetails = checkCredentials(hotelcode);
try {
response.put("hotels", hotelDetails);
response.put("status", (hotelDetails == new JSONArray()) ? "false" : "true");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response.toString();
}
private JSONArray checkCredentials(String hotelcode) {
System.out.println("Inside checkCredentials");
JSONArray result = new JSONArray();
try {
result = DBConnection.checkItems(hotelcode);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static JSONArray checkItems(String hotelcode) throws Exception {
int id;
String code = hotelcode + "_mnu";
String name = null;
String name1 = null;
String status;
String price;
Connection dbConn = null;
Connection dbConn1 = null;
JSONArray hotels = new JSONArray();
JSONArray menu = new JSONArray();
try {
try {
dbConn = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt = dbConn.createStatement();
String query = "SELECT * FROM " + code + " where Status='1'";
System.out.println(query);
ResultSet rs1 = stmt.executeQuery(query);
System.out.println("hai");
while (rs1.next()) {
JSONObject hotel = new JSONObject();
id = rs1.getInt("Id");
hotel.put("id", id);
code = rs1.getString("Code");
System.out.println(code);
hotel.put("code", code);
name = rs1.getString("Name");
hotel.put("name", name);
status = rs1.getString("Status");
hotel.put("status", status);
hotels.put(hotel);
System.out.println("Hotel1:" + hotels);
try {
dbConn1 = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt1 = dbConn1.createStatement();
String query1 = "SELECT * FROM " + code + " where Status='1' ";
System.out.println(query1);
ResultSet rs2 = stmt1.executeQuery(query1);
while (rs2.next()) {
JSONArray hotel1 = new JSONArray();
JSONObject hotelmenu = new JSONObject();
id = rs2.getInt("Id");
hotelmenu.put("id", id);
name1 = rs2.getString("Name");
hotelmenu.put("name", name1);
price = rs2.getString("Price");
hotelmenu.put("price", price);
hotel1.put(hotelmenu);
hotels.put(hotel1);
System.out.println(hotels);
}
}
} catch (SQLException sqle) {
throw sqle;
} catch (Exception e) {
// TODO Auto-generated catch block
if (dbConn != null) {
dbConn.close();
}
throw e;
} finally {
if (dbConn != null) {
dbConn.close();
}
}
return hotels;
}
}
You can do like this:
public class HotelMenu {
public static String crateHotelMenuJson(Statement stmt) throws Exception {
JSONArray hotels = new JSONArray();
JSONObject menu = new JSONObject();
String sql = "SELECT * FROM tb_hotel where Status='1'";
ResultSet hotelResultSet = stmt.executeQuery(sql);
while (hotelResultSet.next()) {
JSONObject hotel = new JSONObject();
hotel.put("id", hotelResultSet.getInt("Id"));
hotel.put("code", hotelResultSet.getString("Code"));
hotel.put("name", hotelResultSet.getString("Name"));
hotel.put("status", hotelResultSet.getString("Status"));
sql = "SELECT * FROM tb_subItem where Status='1' ";
ResultSet subItemResultSet = stmt.executeQuery(sql);
JSONArray subItems = new JSONArray();
while (subItemResultSet.next()) {
JSONObject hotelMenu = new JSONObject();
hotelMenu.put("id", subItemResultSet.getInt("Id"));
hotelMenu.put("name", subItemResultSet.getString("Name"));
hotelMenu.put("price", subItemResultSet.getString("Price"));
subItems.put(hotelMenu);
}
hotel.put("sub_items", subItems);
hotels.put(hotel);
}
menu.put("items", hotels);
JSONObject result = new JSONObject();
result.put("menu", menu);
return result.toString();
}}
I delete the try catch and finally code in order to make the logic more clear.
Don't make it so complex.
Assume you have a simple relation like below,
menu_items(hotel_name text, category text, item text, price number, status boolean)
Now you want to create a JSON response like below,
[
{
hotel : xyz,
menu : {
category : [
{
name : seaFood,
items : [
{
name : fish,
price : 100,
status : 1
},
{
name : friedFish,
price : 150,
status : 1
}
]
},
{
name : breads,
items : [
{
name : roti,
price : 50,
status : 1
},
{
name : naan,
price : 120,
status : 1
}
]
}
]
}
}
]
Generate the same like below code,
JSONArray hotels = new JSONArray();
String query = "SELECT * FROM menu_items where status=true order by hotel, category, item ";
ResultSet rs = stmt.executeQuery(query);
String prevHotel = null;
String prevCategory = null;
JSONObject hotel = null;
JSONObject menu = null;
JSONArray menuCategory = null;
JSONArray menuItems = null;
while (rs.next()) {
String hotelName = rs.getString("hotel_name");
if(prevHotel!=null && hotelName.equals(prevHotel)){
//Do nothing, as given hotel already exist
}else{
prevHotel = hotelName;
hotel = new JSONObject();
hotel.put("hotel", hotelName)
hotels.put(hotel);
menu = new JSONObject();
}
String category = rs.getString("category");
if(prevCategory!=null && prevCategory.equals(hotelName+category)){
//Do nothing, as given category already exist
}else{
prevCategory = hotelName+category;
menuCategory = new JSONArray();
menuCategory.put("name", category);
menu.put("category", menuCategory);
menuItems = new JSONArray();
menuCategory.put("items", menuItems);
}
JSONObject menuItem = new JSONObject();
menuItem.put("name", rs.getString("item"));
menuItem.put("price", rs.getString("price"));
menuItem.put("status", rs.getString("status"));
menuItems.put(menuItem);
}

How to write JSON object in java code?

My Json are following
{
"q": {
"region": "NYC",
"or": [
{
"duration": "12"
}
]
},
"sort": "recent"
}
How to write in JsonObject.I tried with following code:
JSONObject obj = new JSONObject();
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
JSONObject obj4 = new JSONObject();
try {
obj.put("q", obj1);
obj.put("sort", "recent");
obj1.put("reg", "NYC");
obj2.put("duration", new Integer(12));
obj4.put()
} catch (JSONException e) {
}
I got stuck in creating Array of list. How can I convert into Json Object?
You may build the JSONObject in this way:
public class Test {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("q", new JSONObject()
.put("region", "NYC")
.put("or", new JSONArray()
.put(new JSONObject()
.put("duration","12"))))
.put("sort", "recent");
System.out.println(obj);
}
}
The output:
{"q":{"or":[{"duration":"12"}],"region":"NYC"},"sort":"recent"}

Android : Json Parsing show error

[
{
"description": "My home",
"name": "Sweet Home",
"point": {
"lat": 22.890976,
"long": 90.459097
},
"type": 1,
"cid": "5319197376176516414"
}
This is my json file for parsing information. Here is my code for parsing name and lng.
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this.getResources().openRawResource(R.raw.map)));
StringBuilder jsonBuilder = new StringBuilder();
try {
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String title = jsonObject.getString("name");
String lhg = jsonObject.getJSONObject("point").getString("lng");
} catch (FileNotFoundException e) {
Log.e("jsonFile", "file not found");
} catch (IOException e) {
Log.e("jsonFile", "ioerror");
} catch (JSONException e) {
Log.e("jsonFile", "error while parsing json");
}
}
}
It show's me an exception error while parsing json. How do i solve that? What was my problem?
Because "Point" in your JSON object never contains a property called "lng"
String lhg = jsonObject.getJSONObject("point").getString("lng")
it does contain one named "long"
"point": {
"lat": 22.890976,
"long": 90.459097
},
So the code to fetch the longitude should look like this:
String lhg = jsonObject.getJSONObject("point").getString("long")
String lhg = jsonObject.getJSONObject("point").getString("lng") use "long" instead of lng.

Categories

Resources