Nested JSON response dynamically in java - 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);
}

Related

Fetching JSON from inside a JSON array

I have the following JSON
"music": [
{
"play_offset_ms":10780,
"artists":[
{
"name":"Adele"
}
],
"lyrics":{
"copyrights":[
"Sony/ATV Music Publishing LLC",
"Universal Music Publishing Group"
]
},
"acrid":"6049f11da7095e8bb8266871d4a70873",
"album":{
"name":"Hello"
},
"label":"XL Recordings",
"external_ids":{
"isrc":"GBBKS1500214",
"upc":"886445581959"
},
"result_from":3,
"contributors":{
"composers":[
"Adele Adkins",
"Greg Kurstin"
],
"lyricists":[
"ADELE ADKINS",
"GREGORY KURSTIN"
]
},
"title":"Hello",
"duration_ms":295000,
"score":100,
"external_metadata":{
"deezer":{
"track":{
"id":"110265034"
},
"artists":[
{
"id":"75798"
}
],
"album":{
"id":"11483764"
}
},
"spotify":{
"track":{
"id":"4aebBr4JAihzJQR0CiIZJv"
},
"artists":[
{
"id":"4dpARuHxo51G3z768sgnrY"
}
],
"album":{
"id":"7uwTHXmFa1Ebi5flqBosig"
}
},
"musicstory":{
"track":{
"id":"13106540"
},
"release":{
"id":"2105405"
},
"album":{
"id":"931271"
}
},
"youtube":{
"vid":"YQHsXMglC9A"
}
},
"release_date":"2015-10-23"
}
]
I want to fetch the value vid from the youtube object in external_metadata. I am getting other required values but couldn't get the youtube id with what I tried. Just attaching a code snippet of what I tried.
I tried the following code:
try {
JSONObject j = new JSONObject(result);
JSONObject j1 = j.getJSONObject("status");
int j2 = j1.getInt("code");
if(j2 == 0){
JSONObject metadata = j.getJSONObject("metadata");
//
if (metadata.has("music")) {
wave.setVisibility(View.GONE);
JSONArray musics = metadata.getJSONArray("music");
for(int i=0; i<musics.length(); i++) {
JSONObject tt = (JSONObject) musics.get(i);
String title = tt.getString("title");
JSONArray artistt = tt.getJSONArray("artists");
JSONObject art = (JSONObject) artistt.get(0);
String artist = art.getString("name");
JSONObject extMETA = tt.getJSONObject("external_metadata");
JSONObject youtube = extMETA.getJSONObject("youtube");
String ytID = youtube.getString("vid");}}
I did not get the expected output with what i tried , i know i am doing something wrong. Need your guidance.
I tried to run your code with sample JSON you have provided and It seems to work perfectly fine. I used google's gson library.
Below is the complete code.
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String jsonString = "{ \"music\": [{ \"play_offset_ms\": 10780, \"artists\": [{ \"name\": \"Adele\" }], \"lyrics\": { \"copyrights\": [ \"Sony/ATV Music Publishing LLC\", \"Universal Music Publishing Group\" ] }, \"acrid\": \"6049f11da7095e8bb8266871d4a70873\", \"album\": { \"name\": \"Hello\" }, \"label\": \"XL Recordings\", \"external_ids\": { \"isrc\": \"GBBKS1500214\", \"upc\": \"886445581959\" }, \"result_from\": 3, \"contributors\": { \"composers\": [ \"Adele Adkins\", \"Greg Kurstin\" ], \"lyricists\": [ \"ADELE ADKINS\", \"GREGORY KURSTIN\" ] }, \"title\": \"Hello\", \"duration_ms\": 295000, \"score\": 100, \"external_metadata\": { \"deezer\": { \"track\": { \"id\": \"110265034\" }, \"artists\": [{ \"id\": \"75798\" }], \"album\": { \"id\": \"11483764\" } }, \"spotify\": { \"track\": { \"id\": \"4aebBr4JAihzJQR0CiIZJv\" }, \"artists\": [{ \"id\": \"4dpARuHxo51G3z768sgnrY\" }], \"album\": { \"id\": \"7uwTHXmFa1Ebi5flqBosig\" } }, \"musicstory\": { \"track\": { \"id\": \"13106540\" }, \"release\": { \"id\": \"2105405\" }, \"album\": { \"id\": \"931271\" } }, \"youtube\": { \"vid\": \"YQHsXMglC9A\" } }, \"release_date\": \"2015-10-23\" }] }";
public static void main(String[] args) throws Exception {
System.out.println("START");
readJson(jsonString);
System.out.println("END");
}
public static void readJson(String jsonString) throws Exception {
JsonObject metadata = new JsonParser().parse(jsonString).getAsJsonObject();
JsonArray musics = metadata.get("music").getAsJsonArray();
for (int i = 0; i < musics.size(); i++) {
JsonObject tt = musics.get(i).getAsJsonObject();
String title = tt.get("title").getAsString();
JsonArray artistt = tt.get("artists").getAsJsonArray();
JsonObject art = artistt.get(0).getAsJsonObject();
String artist = art.get("name").getAsString();
JsonObject extMETA = tt.get("external_metadata").getAsJsonObject();
JsonObject youtube = extMETA.get("youtube").getAsJsonObject();
String ytID = youtube.get("vid").getAsString();
System.out.println("ytID => "+ ytID);
}
}
}
Output:
Verify that the metadata variable has its value.
JSONObject jsonObject = new JSONObject(json);
Log.e("json structure : ", jsonObject.toString());
Use the following code when importing Json File from "Assets".
InputStream inputStream = getAssets().open("item.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
json = new String(buffer, StandardCharsets.UTF_8);
If you have a Gson library, you can also access it in the "Class" format.
Gson gson = new Gson();
ItemVO itemVO = gson.fromJson(json, new TypeToken<ItemVO>() {
}.getType());
if (!itemVO.name != null) {
Log.e("name : ", itemVO.name);
} else {
Log.e("name : ", "name is Null");
}
Actual problem is in your JSONObject creation from sample data. Check below:
String data = "{\"metadata\":{\"timestamp_utc\":\"2020-01-02 09:40:56\",\"music\":[{\"play_offset_ms\":10780,\"artists\":[{\"name\":\"Adele\"}],\"lyrics\":{\"copyrights\":[\"Sony/ATV Music Publishing LLC\",\"Universal Music Publishing Group\"]},\"acrid\":\"6049f11da7095e8bb8266871d4a70873\",\"album\":{\"name\":\"Hello\"},\"label\":\"XL Recordings\",\"external_ids\":{\"isrc\":\"GBBKS1500214\",\"upc\":\"886445581959\"},\"result_from\":3,\"contributors\":{\"composers\":[\"Adele Adkins\",\"Greg Kurstin\"],\"lyricists\":[\"ADELE ADKINS\",\"GREGORY KURSTIN\"]},\"title\":\"Hello\",\"duration_ms\":295000,\"score\":100,\"external_metadata\":{\"deezer\":{\"track\":{\"id\":\"110265034\"},\"artists\":[{\"id\":\"75798\"}],\"album\":{\"id\":\"11483764\"}},\"spotify\":{\"track\":{\"id\":\"4aebBr4JAihzJQR0CiIZJv\"},\"artists\":[{\"id\":\"4dpARuHxo51G3z768sgnrY\"}],\"album\":{\"id\":\"7uwTHXmFa1Ebi5flqBosig\"}},\"musicstory\":{\"track\":{\"id\":\"13106540\"},\"release\":{\"id\":\"2105405\"},\"album\":{\"id\":\"931271\"}},\"youtube\":{\"vid\":\"YQHsXMglC9A\"}},\"release_date\":\"2015-10-23\"}]},\"cost_time\":0.2110002040863,\"status\":{\"msg\":\"Success\",\"version\":\"1.0\",\"code\":0},\"result_type\":0}";
try {
JSONObject jsonObject = new JSONObject(data);
JSONObject metadata = jsonObject.getJSONObject("metadata");
JSONArray musics = metadata.getJSONArray("music");
for (int i = 0; i < musics.length(); i++) {
JSONObject tt = (JSONObject) musics.get(i);
String title = tt.getString("title");
JSONArray artistt = tt.getJSONArray("artists");
JSONObject art = (JSONObject) artistt.get(0);
String artist = art.getString("name");
JSONObject extMETA = tt.getJSONObject("external_metadata");
JSONObject youtube = extMETA.getJSONObject("youtube");
String ytID = youtube.getString("vid");
Log.v("VID", ytID);
}
} catch (Exception ex) {
ex.printStackTrace();
}

How to read JSON file with Arrays and Objects in Java

I'm trying to read a file which is fetched from Opentdb and access data from only specific keys.
I've tried all of the given methods which includes GSON and Json Simple but ended up having errors.
Here's my JSON:
{
"response_code": 0,
"results": [
{
"category": "Sports",
"type": "multiple",
"difficulty": "easy",
"question": "Which of the following sports is not part of the triathlon?",
"correct_answer": "Horse-Riding",
"incorrect_answers": [
"Cycling",
"Swimming",
"Running"
]
},
{
"category": "Sports",
"type": "multiple",
"difficulty": "easy",
"question": "Which English football club has the nickname \u0026#039;The Foxes\u0026#039;?",
"correct_answer": "Leicester City",
"incorrect_answers": [
"Northampton Town",
"Bradford City",
"West Bromwich Albion"
]
},
I want to access only category, difficulty, question , correct_answer and incorrect_answers .
excample for you
try {
URL resource = App.class.getClassLoader().getResource("info.json");
System.out.println(resource.toString());
FileReader reader = new FileReader(resource.getFile());
// Read JSON file
Object obj = jsonParser.parse(reader);
JSONArray infoList = (JSONArray) obj;
System.out.println(infoList);
Information i = new Information();
List<Information> info = i.parseInformationObject(infoList);
saveInformation(info);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
and
List<Information> parseInformationObject(JSONArray infoList) {
List<Information> in = new ArrayList<>();
infoList.forEach(emp -> {
JSONObject info = (JSONObject) emp;
String id = info.get("id").toString();
String state = info.get("state").toString();
String type = null;
if (info.get("type") != null) {
type = info.get("type").toString();
}
String host = null;
if (info.get("host") != null) {
host = info.get("host").toString();
}
long timestamp = (long) info.get("timestamp");
in.add(new Information(id, state, type, host, timestamp));
});
return in;
}

Nested JSON Array 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 will give 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;
}
}
As previous answers suggests, you should re-design your model. I just did a quick restructuring of it. Check if this serves your purpose -
{
"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"
}]
}
]
}}
If the structure is OK, let know if you want help with the Java code to generate the above Json.
Also maybe go through the following libraries -
Jackson tutorial and Gson tutorial
//import java.util.ArrayList;
//import org.bson.Document;
Document root = new Document();
Document rootMenu = new Document();
ArrayList rootMenuItems = new ArrayList();
Document rootMenuItems0 = new Document();
ArrayList rootMenuItems0Sub_items = new ArrayList();
Document rootMenuItems0Sub_items0 = new Document();
Document rootMenuItems0Sub_items1 = new Document();
Document rootMenuItems1 = new Document();
ArrayList rootMenuItems1Sub_items = new ArrayList();
Document rootMenuItems1Sub_items0 = new Document();
Document rootMenuItems2 = new Document();
ArrayList rootMenuItems2Sub_items = new ArrayList();
Document rootMenuItems2Sub_items0 = new Document();
Document rootMenuItems2Sub_items1 = new Document();
rootMenuItems0.append("id", 1);
rootMenuItems0.append("code", "hot1_sub1_mnu");
rootMenuItems0.append("name", "Mutton");
rootMenuItems0.append("status", "1");
rootMenuItems0Sub_items0.append("id", "01");
rootMenuItems0Sub_items0.append("name", "Mutton Pepper Fry");
rootMenuItems0Sub_items0.append("price", "100");
rootMenuItems0Sub_items1.append("id", "02");
rootMenuItems0Sub_items1.append("name", "Mutton Curry");
rootMenuItems0Sub_items1.append("price", "100");
rootMenuItems1.append("id", "2");
rootMenuItems1.append("code", "hot1_sub2_mnu");
rootMenuItems1.append("name", "Sea Food");
rootMenuItems1.append("status", "1");
rootMenuItems1Sub_items0.append("id", "01");
rootMenuItems1Sub_items0.append("name", "Fish Fry");
rootMenuItems1Sub_items0.append("price", "150");
rootMenuItems2.append("id", "3");
rootMenuItems2.append("code", "hot1_sub3_mnu");
rootMenuItems2.append("name", "Noodles");
rootMenuItems2.append("status", "1");
rootMenuItems2Sub_items0.append("id", "01");
rootMenuItems2Sub_items0.append("name", "Chicken Noodles");
rootMenuItems2Sub_items0.append("price", "70");
rootMenuItems2Sub_items1.append("id", "02");
rootMenuItems2Sub_items1.append("name", "Egg Noodles");
rootMenuItems2Sub_items1.append("price", "60");
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenuItems0Sub_items.isEmpty()) {
rootMenuItems0.append("sub_items", rootMenuItems0Sub_items);
}
if (!rootMenuItems0Sub_items0.isEmpty()) {
rootMenuItems0Sub_items.add(rootMenuItems0Sub_items0);
}
if (!rootMenuItems0Sub_items.isEmpty()) {
rootMenuItems0.append("sub_items", rootMenuItems0Sub_items);
}
if (!rootMenuItems0Sub_items1.isEmpty()) {
rootMenuItems0Sub_items.add(rootMenuItems0Sub_items1);
}
if (!rootMenuItems0Sub_items.isEmpty()) {
rootMenuItems0.append("sub_items", rootMenuItems0Sub_items);
}
if (!rootMenuItems0.isEmpty()) {
rootMenuItems.add(rootMenuItems0);
}
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenuItems1Sub_items.isEmpty()) {
rootMenuItems1.append("sub_items", rootMenuItems1Sub_items);
}
if (!rootMenuItems1Sub_items0.isEmpty()) {
rootMenuItems1Sub_items.add(rootMenuItems1Sub_items0);
}
if (!rootMenuItems1Sub_items.isEmpty()) {
rootMenuItems1.append("sub_items", rootMenuItems1Sub_items);
}
if (!rootMenuItems1.isEmpty()) {
rootMenuItems.add(rootMenuItems1);
}
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenuItems2Sub_items.isEmpty()) {
rootMenuItems2.append("sub_items", rootMenuItems2Sub_items);
}
if (!rootMenuItems2Sub_items0.isEmpty()) {
rootMenuItems2Sub_items.add(rootMenuItems2Sub_items0);
}
if (!rootMenuItems2Sub_items.isEmpty()) {
rootMenuItems2.append("sub_items", rootMenuItems2Sub_items);
}
if (!rootMenuItems2Sub_items1.isEmpty()) {
rootMenuItems2Sub_items.add(rootMenuItems2Sub_items1);
}
if (!rootMenuItems2Sub_items.isEmpty()) {
rootMenuItems2.append("sub_items", rootMenuItems2Sub_items);
}
if (!rootMenuItems2.isEmpty()) {
rootMenuItems.add(rootMenuItems2);
}
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenu.isEmpty()) {
root.append("menu", rootMenu);
}
System.out.println(root.toJson());

How to parse login response in android?

I am confused about parsing so I want to know about how to parse. Whenever I login with valid login id and password give response
{
"data": {
"status": "1",
"Full Name": [
{
"user_id": 1,
"user_name": "deepika#soms.in",
"full_name": "",
"display_name": "",
"token": "",
"photo_url": "http://clients.vfactor.in/putt2gether/images/profile/default.jpg"
}
],
"Event": [
{
"latest_event_id": "",
"format_id": ""
}
],
"msg": "Success Login"
}
}
and if invalid login id then give response
{
"Error": {
"msg": "Please Enter valid Email Address"
}
try {
JSONObject obj = new JSONObject(response);
if (obj.has("Error")) {
JSONObject objError = obj.getJSONObject("Error");
} else if (obj.has("data")) {
JSONObject objData = obj.getJSONObject("data");
}
} catch (Exception e) {
e.printStackTrace();
}
You need to parse the json answer.
There are many sources to learn how to do that:
Oracle documentation
Jackson documentation - Jackson is a library to parse json
GSon documentation - Another json parser
Let's assume response be,
String response;
try
{
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("data"))
{
JSONObject jsonObjData = jsonObject.getJSONObject("data");
String status = jsonObject.getString("status");
JSONArray jsonArrayName = jsonObjData.getJSONArray("Full Name");
for (int i = 0; i < jsonArrayName.length(); i++) {
JSONObject jsonObj = jsonArrayName.getJSONObject(i);
Integer user_id = jsonObj.getInt("user_id");
String user_name = jsonObj.getString("user_name");
String full_name = jsonObj.getString("full_name");
String display_name = jsonObj.getString("display_name");
String photo_url = jsonObj.getString("photo_url");
}
JSONArray jsonArrayEvent = jsonObjData.getJSONArray("Event");
for (int i = 0; i < jsonArrayEvent.length(); i++) {
JSONObject jsonObj = jsonArrayEvent.getJSONObject(i);
String latest_event_id = jsonObj.getString("latest_event_id");
String format_id = jsonObj.getString("format_id");
}
String msg = jsonObject.getString("msg");
} else if (jsonObject.has("Error")) {
JSONObject jsonObjError = jsonObject.getJSONObject("Error");
String msg = jsonObjError.getString("msg");
}
} catch (Exception e) {
e.printStackTrace();
}

How can I parse a local JSON file from assets folder into a ListView?

I'm currently developing a physics app that is supposed to show a list of formulas and even solve some of them (the only problem is the ListView)
This is my main layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:measureWithLargestChild="false"
android:orientation="vertical"
tools:context=".CatList">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/titlebar">
<TextView
android:id="#+id/Title1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ff1c00"
android:textIsSelectable="false" />
</RelativeLayout>
<ListView
android:id="#+id/listFormulas"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
And this is my main activity
package com.wildsushii.quickphysics;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.view.Menu;
import android.widget.ListView;
public class CatList extends Activity {
public static String AssetJSONFile(String filename, Context context) throws IOException {
AssetManager manager = context.getAssets();
InputStream file = manager.open(filename);
byte[] formArray = new byte[file.available()];
file.read(formArray);
file.close();
return new String(formArray);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cat_list);
ListView categoriesL = (ListView) findViewById(R.id.listFormulas);
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
Context context = null;
try {
String jsonLocation = AssetJSONFile("formules.json", context);
JSONObject formArray = (new JSONObject()).getJSONObject("formules");
String formule = formArray.getString("formule");
String url = formArray.getString("url");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
//My problem is here!!
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cat_list, menu);
return true;
}
}
I actually know I can make this without using JSON but I need more practice parsing JSON. By the way, this is the JSON
{
"formules": [
{
"formule": "Linear Motion",
"url": "qp1"
},
{
"formule": "Constant Acceleration Motion",
"url": "qp2"
},
{
"formule": "Projectile Motion",
"url": "qp3"
},
{
"formule": "Force",
"url": "qp4"
},
{
"formule": "Work, Power, Energy",
"url": "qp5"
},
{
"formule": "Rotary Motion",
"url": "qp6"
},
{
"formule": "Harmonic Motion",
"url": "qp7"
},
{
"formule": "Gravity",
"url": "qp8"
},
{
"formule": "Lateral and Longitudinal Waves",
"url": "qp9"
},
{
"formule": "Sound Waves",
"url": "qp10"
},
{
"formule": "Electrostatics",
"url": "qp11"
},
{
"formule": "Direct Current",
"url": "qp12"
},
{
"formule": "Magnetic Field",
"url": "qp13"
},
{
"formule": "Alternating Current",
"url": "qp14"
},
{
"formule": "Thermodynamics",
"url": "qp15"
},
{
"formule": "Hydrogen Atom",
"url": "qp16"
},
{
"formule": "Optics",
"url": "qp17"
},
{
"formule": "Modern Physics",
"url": "qp18"
},
{
"formule": "Hydrostatics",
"url": "qp19"
},
{
"formule": "Astronomy",
"url": "qp20"
}
]
}
I have tried a lot of things and even delete the entire project to make a new one :(
As Faizan describes in their answer here:
First of all read the Json File from your assests file using below code.
and then you can simply read this string return by this function as
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and use this method like that
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray("formules");
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
Log.d("Details-->", jo_inside.getString("formule"));
String formula_value = jo_inside.getString("formule");
String url_value = jo_inside.getString("url");
//Add your values in your `ArrayList` as below:
m_li = new HashMap<String, String>();
m_li.put("formule", formula_value);
m_li.put("url", url_value);
formList.add(m_li);
}
} catch (JSONException e) {
e.printStackTrace();
}
For further details regarding JSON Read HERE
With Kotlin have this extension function to read the file return as string.
fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}
Parse the output string using any JSON parser.
{ // json object node
"formules": [ // json array formules
{ // json object
"formule": "Linear Motion", // string
"url": "qp1"
}
What you are doing
Context context = null; // context is null
try {
String jsonLocation = AssetJSONFile("formules.json", context);
So change to
try {
String jsonLocation = AssetJSONFile("formules.json", CatList.this);
To parse
I believe you get the string from the assests folder.
try
{
String jsonLocation = AssetJSONFile("formules.json", context);
JSONObject jsonobject = new JSONObject(jsonLocation);
JSONArray jarray = (JSONArray) jsonobject.getJSONArray("formules");
for(int i=0;i<jarray.length();i++)
{
JSONObject jb =(JSONObject) jarray.get(i);
String formula = jb.getString("formule");
String url = jb.getString("url");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Just summarising #libing's answer with a sample that worked for me.
val gson = Gson()
val todoItem: TodoItem = gson.fromJson(this.assets.readAssetsFile("versus.json"), TodoItem::class.java)
private fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}
Without this extension function the same can be achieved by using BufferedReader and InputStreamReader this way:
val i: InputStream = this.assets.open("versus.json")
val br = BufferedReader(InputStreamReader(i))
val todoItem: TodoItem = gson.fromJson(br, TodoItem::class.java)
Method to read JSON file from Assets folder and return as a string object.
public static String getAssetJsonData(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("myJson.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
Log.e("data", json);
return json;
}
Now for parsing data in your activity:-
String data = getAssetJsonData(getApplicationContext());
Type type = new TypeToken<Your Data model>() {
}.getType();
<Your Data model> modelObject = new Gson().fromJson(data, type);
If you are using Kotlin in android then you can create Extension function.
Extension Functions are defined outside of any class - yet they reference the class name and can use this. In our case we use applicationContext.
So in Utility class you can define all extension functions.
Utility.kt
fun Context.loadJSONFromAssets(fileName: String): String {
return applicationContext.assets.open(fileName).bufferedReader().use { reader ->
reader.readText()
}
}
MainActivity.kt
You can define private function for load JSON data from assert like this:
lateinit var facilityModelList: ArrayList<FacilityModel>
private fun bindJSONDataInFacilityList() {
facilityModelList = ArrayList<FacilityModel>()
val facilityJsonArray = JSONArray(loadJSONFromAsserts("NDoH_facility_list.json")) // Extension Function call here
for (i in 0 until facilityJsonArray.length()){
val facilityModel = FacilityModel()
val facilityJSONObject = facilityJsonArray.getJSONObject(i)
facilityModel.Facility = facilityJSONObject.getString("Facility")
facilityModel.District = facilityJSONObject.getString("District")
facilityModel.Province = facilityJSONObject.getString("Province")
facilityModel.Subdistrict = facilityJSONObject.getString("Facility")
facilityModel.code = facilityJSONObject.getInt("code")
facilityModel.gps_latitude = facilityJSONObject.getDouble("gps_latitude")
facilityModel.gps_longitude = facilityJSONObject.getDouble("gps_longitude")
facilityModelList.add(facilityModel)
}
}
You have to pass facilityModelList in your ListView
FacilityModel.kt
class FacilityModel: Serializable {
var District: String = ""
var Facility: String = ""
var Province: String = ""
var Subdistrict: String = ""
var code: Int = 0
var gps_latitude: Double= 0.0
var gps_longitude: Double= 0.0
}
In my case JSON response start with JSONArray
[
{
"code": 875933,
"Province": "Eastern Cape",
"District": "Amathole DM",
"Subdistrict": "Amahlathi LM",
"Facility": "Amabele Clinic",
"gps_latitude": -32.6634,
"gps_longitude": 27.5239
},
{
"code": 455242,
"Province": "Eastern Cape",
"District": "Amathole DM",
"Subdistrict": "Amahlathi LM",
"Facility": "Burnshill Clinic",
"gps_latitude": -32.7686,
"gps_longitude": 27.055
}
]
Using OKIO
implementation("com.squareup.okio:okio:3.0.0-alpha.4")
With Java:
public static String readJsonFromAssets(Context context, String filePath) {
try {
InputStream input = context.getAssets().open(filePath);
BufferedSource source = Okio.buffer(Okio.source(input));
return source.readByteString().string(Charset.forName("utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
With Kotlin:
fun readJsonFromAssets(context: Context, filePath: String): String? {
try {
val source = context.assets.open(filePath).source().buffer()
return source.readByteString().string(Charset.forName("utf-8"))
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
and then...
String data = readJsonFromAssets(context, "json/some.json"); //here is my file inside the folder assets/json/some.json
Type reviewType = new TypeToken<List<Object>>() {}.getType();
if (data != null) {
Object object = new Gson().fromJson(data, reviewType);
}
Source code How to fetch Local Json from Assets folder
https://drive.google.com/open?id=1NG1amTVWPNViim_caBr8eeB4zczTDK2p
{
"responseCode": "200",
"responseMessage": "Recode Fetch Successfully!",
"responseTime": "10:22",
"employeesList": [
{
"empId": "1",
"empName": "Keshav",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "9654267338",
"empDesignation": "Sr. Java Developer",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "2",
"empName": "Ram",
"empFatherName": "Mr Dasrath ji",
"empSalary": "9999999999",
"empDesignation": "Sr. Java Developer",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "3",
"empName": "Manisha",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "8826420999",
"empDesignation": "BusinessMan",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "4",
"empName": "Happy",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "9582401701",
"empDesignation": "Two Wheeler",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "5",
"empName": "Ritu",
"empFatherName": "Mr Keshav Gera",
"empSalary": "8888888888",
"empDesignation": "Sararat Vibhag",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
}
]
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee);
emp_recycler_view = (RecyclerView) findViewById(R.id.emp_recycler_view);
emp_recycler_view.setLayoutManager(new LinearLayoutManager(EmployeeActivity.this,
LinearLayoutManager.VERTICAL, false));
emp_recycler_view.setItemAnimator(new DefaultItemAnimator());
employeeAdapter = new EmployeeAdapter(EmployeeActivity.this , employeeModelArrayList);
emp_recycler_view.setAdapter(employeeAdapter);
getJsonFileFromLocally();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = EmployeeActivity.this.getAssets().open("employees.json"); //TODO Json File name from assets folder
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void getJsonFileFromLocally() {
try {
JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
String responseCode = jsonObject.getString("responseCode");
String responseMessage = jsonObject.getString("responseMessage");
String responseTime = jsonObject.getString("responseTime");
Log.e("keshav", "responseCode -->" + responseCode);
Log.e("keshav", "responseMessage -->" + responseMessage);
Log.e("keshav", "responseTime -->" + responseTime);
if(responseCode.equals("200")){
}else{
Toast.makeText(this, "No Receord Found ", Toast.LENGTH_SHORT).show();
}
JSONArray jsonArray = jsonObject.getJSONArray("employeesList"); //TODO pass array object name
Log.e("keshav", "m_jArry -->" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++)
{
EmployeeModel employeeModel = new EmployeeModel();
JSONObject jsonObjectEmployee = jsonArray.getJSONObject(i);
String empId = jsonObjectEmployee.getString("empId");
String empName = jsonObjectEmployee.getString("empName");
String empDesignation = jsonObjectEmployee.getString("empDesignation");
String empSalary = jsonObjectEmployee.getString("empSalary");
String empFatherName = jsonObjectEmployee.getString("empFatherName");
employeeModel.setEmpId(""+empId);
employeeModel.setEmpName(""+empName);
employeeModel.setEmpDesignation(""+empDesignation);
employeeModel.setEmpSalary(""+empSalary);
employeeModel.setEmpFatherNamer(""+empFatherName);
employeeModelArrayList.add(employeeModel);
} // for
if(employeeModelArrayList!=null) {
employeeAdapter.dataChanged(employeeModelArrayList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You have to write a function to read the Json File from your assests folder.
public String loadJSONFile() {
String json = null;
try {
InputStream inputStream = getAssets().open("yourfilename.json");
int size = inputStream.available();
byte[] byteArray = new byte[size];
inputStream.read(byteArray);
inputStream.close();
json = new String(byteArray, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}

Categories

Resources