How to get and set JSONObject , JSONArray in J2ME - java

I am new to JSON programming in J2ME.
I discovered that Json is used to exchange data much like XML.
I want to know about the exchange in Array object from JSONtoObject and vice versa
Below written is code where I convert from JSON to Object and vice versa.
But I don't know about how to do for complex data structure like arrays etc.
// App Loader
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class AppLoader extends MIDlet {
public AppLoader() {
// TODO Auto-generated constructor stub
// Converting Object to JSON
UserData data=new UserData();
data.setId(10);
data.setName("Yatin");
data.setDescription("Testing JSON in J2ME");
System.out.println("Convert to JSON"+data.toJSON());
//Convert JSON to Object
String sample="{\"id\":99,\"name\":\"Tester\",\"description\":\"This is JSON Data\"}";
UserData data2=new UserData();
data2.fromJSON(sample);
System.out.println("Convert from JSON "+data2);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
}
In this class I created getters and setters for the String type of objects and then created JsonObject to create a JSON object to create a JSON object and then vice versa as per functions toJSON() and fromJSON()
// User Data class
import org.json.me.JSONException;
import org.json.me.JSONObject;
public class UserData {
private int id;
private String name;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString()
{
return getId()+"-"+getName()+"-"+getDescription();
}
public String toJSON() {
// TODO Auto-generated method stub
JSONObject inner=new JSONObject();
try {
inner.put("id",getId());
inner.put("description", getDescription());
inner.put("name", getName());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inner.toString();
}
public void fromJSON(String jsonString) {
// TODO Auto-generated method stub
try {
JSONObject json=new JSONObject(jsonString);
setId(json.getInt("id"));
setDescription(json.getString("description"));
setName(json.getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
i found a better link for this question
http://jimmod.com/blog/2011/09/java-me-j2me-json-implementation-for-array-object/

Check this link for different JSON Data Set Sample
One Example for your Understanding::: JSON String Nested with Arrays
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
To check its valid or not check this link (JSON Validator)
To check JSON Viewer
So Here is code take look::
String json = "{\"id\":\"0001\",\"type\":\"donut\",\"name\":\"Cake\""
+ ",\"ppu\":0.55,\"batters\":{\"batter\":["
+ "{\"id\":\"1001\",\"type\":\"Regular\"},{\"id\":\"1002\","
+ "\"type\":\"Chocolate\"},{\"id\":\"1003\","
+ "\"type\": \"Blueberry\" },{ \"id\": \"1004\", "
+ "\"type\": \"Devil's Food\" } ] },"
+ " \"topping\":["
+ "{ \"id\": \"5001\", \"type\": \"None\" },"
+ "{ \"id\": \"5002\", \"type\": \"Glazed\" },"
+ "{ \"id\": \"5005\", \"type\": \"Sugar\" },"
+ "{ \"id\": \"5007\", \"type\": \"Powdered Sugar\" },"
+ " { \"id\": \"5006\", \"type\": \"Chocolate with Sprinkles\" },"
+ "{ \"id\": \"5003\", \"type\": \"Chocolate\" },"
+ "{ \"id\": \"5004\", \"type\": \"Maple\" }]}";
try {
JSONObject root = new JSONObject(json);
String id = root.getString("id");
double dd = root.getDouble("ppu");
System.out.println(""+id);
System.out.println(""+dd);
JSONObject batters=new JSONObject(root.getString("batters"));
JSONArray batter=new JSONArray(batters.getString("batter"));
for(int j=0;j<batter.length();j++){
JSONObject navgt_batter=new JSONObject(batter.getString(j));
String id_batter= navgt_batter.getString("id");
String type_batter=navgt_batter.getString("type");
System.out.println(""+id+" "+type_batter);
}
JSONArray topping=root.getJSONArray("topping");
for(int k=0;k<topping.length();k++){
JSONObject navgt_batter=new JSONObject(topping.getString(k));
String id_top =navgt_batter.getString("id");
String type_top=navgt_batter.getString("type");
System.out.println(""+id_top+" "+type_top);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
You can use your same concept to set & get data like above you did. complex data structure always easy to handle in JSON, don't worry about it. Thanks

In the below link
http://jimmod.com/blog/2011/09/java-me-j2me-json-implementation-for-array-object/
they have explained how a JSONArray is used
public void fromJSON(String jsonString) {
try {
JSONObject json = new JSONObject(jsonString);
setApi_status(json.getString("api_status"));
JSONArray jsonArray = json.getJSONArray("threads");
int total = jsonArray.length();
ThreadData[] threads = new ThreadData[total];
for (int i=0;i<total;i++) {
String threadsJSON = jsonArray.getString(i);
threads[i] = new ThreadData();
threads[i].fromJSON(threadsJSON);
}
setThreads(threads);
} catch (JSONException ex) {
ex.printStackTrace();
}
}
public String toJSON() {
JSONObject inner = new JSONObject();
try {
inner.put("api_status", getApi_status());
JSONArray jsonArray = new JSONArray();
ThreadData[] threads = getThreads();
for (int i=0;i<threads.length;i++) {
jsonArray.put(threads[i].toJSON());
}
inner.put("threads", jsonArray);
} catch (JSONException ex) {
ex.printStackTrace();
}
return inner.toString();
}
Where Threaddata is a class defined for a JSONObject and it has been made in array object
check out the link

It pretty the same way .. all you need is to just loop through the array ... i added tags to your sample JSON data
String sample = "{\"id\":99,\"name\":\"Tester\",\"description\":\"This is JSON Data\",\"tags\":[\"eat\",\"swim\",\"sleep\"]}";
try {
JSONObject objSample = new JSONObject(sample);
JSONArray array = new JSONArray(objSample.getJSONArray("tags").toString());
System.out.println(objSample.get("id").toString());
System.out.println(objSample.get("name").toString());
System.out.println(objSample.get("description").toString());
for (int i = 0; i < array.length(); i++) {
System.out.println(array.get(i).toString());
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Output
99
Tester
This is JSON Data
eat
swim
sleep
I hope this helps
Thanks
:)

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;
}

Array inside an array - Java Codes

I am new at programming. I have this problem of fetching the values from sub array entitled "subresult". I have code of getting values from an array but it seems that it only gets the outer array and disregard the inner array. It is sad that I have no luck in this. Please respect my question because I'm just a beginner. Hoping an answer from you guys. Thank you!
JSON:
{
"result":[
{
"commonname":"Tamaraw",
"subresult":[
{
"latitude":"13.088847376649245",
"longitude":"121.0535496566772",
"province":"Mindoro"
},
{
"latitude":"14.898346071682198",
"longitude":"121.42616213302608",
"province":"General nakar"
},
{
"latitude":"14.44133541176629",
"longitude":"120.45936525802608",
"province":"Bataan"
}
]
},
{
"commonname":"Philippine Tarsier",
"subresult":[
{
"latitude":"9.810806171435631",
"longitude":"124.26143093023506",
"province":"Bohol"
}
]
},
{
"commonname":"Philippine Eagle",
"subresult":[
{
"latitude":"7.2396901503428",
"longitude":"125.44315069027664",
"province":"Davao City"
}
]
},
{
"commonname":"Visayan Warty Pig",
"subresult":[
{
"latitude":"9.651642644962154",
"longitude":"122.84131398239595",
"province":"Panay And Negros"
}
]
},
{
"commonname":"Philippine Fresh Water Crocodile",
"subresult":[
{
"latitude":"13.093068957060206",
"longitude":"121.06598892373722",
"province":"Mindoro"
}
]
},
{
"commonname":"Walden's Hornbill",
"subresult":[
{
"latitude":"10.071930427284427",
"longitude":"125.59779391691245",
"province":"Camiguin Sur and Dinagat Island"
},
{
"latitude":"14.656674396646768",
"longitude":"121.05812014083858",
"province":"Quezon"
}
]
},
{
"commonname":"Philippine Cockatoo",
"subresult":[
{
"latitude":"9.380944735295179",
"longitude":"118.38456063371927",
"province":"Palawan"
},
{
"latitude":"15.491670747921509",
"longitude":"120.94052188562534",
"province":"Cabanatuan City"
},
{
"latitude":"15.378556159943873",
"longitude":"121.39594973068233",
"province":"Dingalan"
}
]
},
{
"commonname":"Negros Bleeding-heart",
"subresult":[
{
"latitude":"9.551081019434731",
"longitude":"123.09185859510103",
"province":"Negros and Panay"
}
]
},
{
"commonname":"Philippine naked-backed fruit bat",
"subresult":[
{
"latitude":"9.646007526813666",
"longitude":"122.85255472090171",
"province":"Negros"
}
]
},
{
"commonname":"Philippine Forest Turtle",
"subresult":[
{
"latitude":"9.35368808473656",
"longitude":"118.36544272849846",
"province":"Palawan"
}
]
},
{
"commonname":"Dinagat bushy-tailed Cloud Rat",
"subresult":[
{
"latitude":"10.100726050965035",
"longitude":"125.59963979398412",
"province":"Dinagat Island"
}
]
},
{
"commonname":"Hawksbill Sea Turtle",
"subresult":[
{
"latitude":"6.984796116278719",
"longitude":"122.02642351890961",
"province":"Zamboanga"
}
]
},
{
"commonname":"Philippine Spotted Deer",
"subresult":[
{
"latitude":"16.229997551983594",
"longitude":"120.52623997214562",
"province":"Baguio"
}
]
}
]
}
Java code:
public JSONArray result;
public static final String JSON_ARRAY = "result";
public static final String TAG_COMMONNAME= "commonname";
public void getData(){
//Creating a string request
StringRequest stringRequests = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jo = null;
try {
//Parsing the fetched Json String to JSON Object
jo = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = jo.getJSONArray(JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getAnimals(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequests);
}
public void getAnimals(JSONArray ja){
//Traversing through all the items in the json array
for(int i=0;i<ja.length();i++){
try {
//Getting json object
json = ja.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(TAG_COMMONNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getAnimals(JSONArray ja){
//Traversing through all the items in the json array
for(int i=0;i<ja.length();i++){
try {
//Getting json object
json = ja.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(TAG_COMMONNAME));
//TRY THIS
JsonArray subResultJsonArray = json.optJSONArray("subresult");
} catch (JSONException e) {
e.printStackTrace();
}
}

How to get ArrayList using GET method of volley

This is the example of ArrayList that i need to fetch, how to fetch this Arrays? Im using GET method of volley to fetch this Array and show in Recycler View.
[
{
"_id": "a2a1",
"name": "Flower",
"image": {
"_id": "a2a2",
"name": "flower.jpg",
"url": "/uploads/c8c8c.jpg",
"related": [
"a2a1"
],
"id": "0a2a2"
},
},
{
"_id": "433d",
"name": "Bouquet",
"id": "433d",
"image": {
"_id": "433e",
"name": "baloon.jpg",
"url": "/uploads/247db.jpg",
"related": [
"433d"
],
"id": "433e"
},
}]
This is my code by using Get method of Volley to fetch the array, i already put the correct api but i didnt get the list of the array.
private void FlowerList(){
StringRequest request = new StringRequest(
Request.Method.GET,
ServerApi.URL_FLOWER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Gson gson = new GsonBuilder().create();
if(response != null) {
JSONObject json = null;
try {
json = new JSONObject(response);
FlowerModel[] models = gson.fromJson(String.valueOf(json.getJSONArray(null)), FlowerModel[].class);
flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(getContext()).add(request);
}
if you are using Gson verson 2.8' then
try {
json = new JSONObject(response);
ArrayList<FlowerModel> models = gson.fromJson(response, TypeToken.getParameterized(ArrayList.class, FlowerModel.class).getType());
//flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
for older version
try {
json = new JSONObject(response);
ArrayList<FlowerModel> models = gson.fromJson(response, new TypeToken<ArrayList<FlowerModel>>(){}.getType(););
//flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
try this....i have modified your code
ArrayList<String> stringArrayList;
String id1,name,id2;
StringRequest request = new StringRequest(
Request.Method.GET,
ServerApi.URL_FLOWER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Gson gson = new GsonBuilder().create();
if(response != null) {
JSONObject json = null;
try {
json = new JSONObject(response);
JSONArray jsonArray=json.getJSONArray("Your_response_arrayName");
stringArrayList=new ArrayList<>();
for(i=0;i<jsonArray.length;i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
stringArrayList.add(jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(getContext()).add(request);
}
hope this will help you

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);
}

Categories

Resources