I'm developing an Android application that consumes data from a Json API. That Json API returns a array of objects like this:
[
{
"idProduct": 1,
"price": 25.9,
"tpPrice": v1
},
{
"idProduct": 1,
"price": 29.9,
"tpPrice": v2
},
{
"idProduct": 2,
"price": 19.9,
"tpPrice": v1
},
{...}
]
As you can see, the API returns two objects with the same ID, but with different prices.
I want to implement a solution that I can modify this json to something like this:
[
{
"idProduct": 1,
"prices": [
{
"price": "25.9,
"tpPrice": v1
},
{
"price": "29.9,
"tpPrice": v2
}
]
},
{
"idProduct": 2,
"prices" [
{
"price": "19.9,
"tpPrice": v1
}
]
},
{...}
]
Thats my WebServiceManager if its necessary, I'm using Gson.
public class WebServiceManager extends AsyncTask<String, String, List<Object>> {
private IWebServiceManager iWebServiceMngr;
private Context ctx;
private ProgressDialog progress;
private String messageError = null;
private String bean = null;
//private final String URL = "http://192.168.7.1:8080/WSPrePedidos/api/consulta/";
private final String URL_BASE = "/WSPrePedidos/api/consulta/";
private final String PATH = "br.com.example.model.";
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(ctx);
progress.setCancelable(false);
progress.setMessage(ctx.getString(R.string.progress_start));
progress.show();
}
/**
* 0 - Access
* 1 - Parameters
* 2 - Class
*
* #param params
* #return
*/
#Override
protected List<Object> doInBackground(String... params) {
bean = params[2].toString();
publishProgress(ctx.getString(R.string.progress_middle));
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
List<Object> lstObj = new ArrayList<>();
try {
URL url = new URL(params[0] + URL_BASE + params[1]);
Log.i("URL: ", url.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(50000);
urlConnection.setReadTimeout(50000);
urlConnection.connect();
int cdResposta = urlConnection.getResponseCode();
InputStream inputStream;
if (cdResposta < HttpURLConnection.HTTP_BAD_REQUEST) {
Log.i("InputStream Ok: ", "" + cdResposta);
inputStream = urlConnection.getInputStream();
} else {
Log.i("InputStream ferrado: ", "" + cdResposta);
inputStream = urlConnection.getErrorStream();
messageError = ctx.getString(R.string.message_fail_generic);
}
reader = new BufferedReader(new InputStreamReader(inputStream));
JsonElement je = new JsonParser().parse(reader);
Gson gson = new Gson();
if (!je.isJsonObject()) {
for (JsonElement element : je.getAsJsonArray()) {
lstObj.add(gson.fromJson(element.getAsJsonObject(), Class.forName(PATH + bean)));
}
} else if (je.isJsonObject()) {
messageError = null;
JsonObject jsonObject = je.getAsJsonObject();
if (jsonObject.get("error") == null) {
lstObj.add(gson.fromJson(je.getAsJsonObject(), Class.forName(PATH + bean)));
}
}
} catch (Exception e) {
e.printStackTrace();
messageError = ctx.getString(R.string.message_fail_connect_server);
} finally {
try {
if (urlConnection != null)
urlConnection.disconnect();
if (reader != null)
reader.close();
} catch (IOException e1) {
//e1.printStackTrace();
}
}
return lstObj;
}
#Override
protected void onProgressUpdate(String... params) {
progress.setMessage(params[0]);
}
#Override
protected void onPostExecute(List<Object> lstObj) {
super.onPostExecute(lstObj);
iWebServiceMngr.posExecuteAsyncTaskResult(lstObj, bean, messageError);
progress.dismiss();
}
public WebServiceManager(Context ctx, IWebServiceManager iWebServiceMngr) {
this.ctx = ctx;
this.iWebServiceMngr = iWebServiceMngr;
}
}
Sorry for my bad english.
I tried to be as specific as possible.
Create a "Product" Object that contains a map of prices. On your JSON response iterate through it and use the logic:
If a product doesn't exist, create the product and apply the price.
If it does exist and the price ID also does, overwrite the price.
If it does exist and the price ID doesn't exists, add the price to the map.
Related
I am trying to get JSON data from a JSON array which looks like this:
{
"common": [
{
"food_name": "eggs",
"serving_unit": "large",
"tag_name": "raw eggs",
"serving_qty": 1,
"common_type": null,
"tag_id": "775",
"photo": {
"thumb": "https://d2xdmhkmkbyw75.cloudfront.net/775_thumb.jpg"
},
"locale": "en_US"
},
Here's what I am using:
public class GetDietData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
String calories = "UNDEFINED";
try {
URL urlForGetRequest = new URL("https://trackapi.nutritionix.com/v2/search/instant?query=egg");
HttpURLConnection connection = (HttpURLConnection) urlForGetRequest.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("x-app-key", "REMOVED");
connection.addRequestProperty("x-app-id", "REMOVED");
InputStream stream = new BufferedInputStream(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject jsonRes = new JSONObject();
JSONArray common = jsonRes.getJSONArray("common");
for (int i=0; i<common.length(); i++)
{
JSONObject jsonObj = common.getJSONObject(i);
calories = jsonObj.getString("food_name");
}
connection.disconnect();
} catch (IOException | JSONException e) {
editText=(findViewById(R.id.editTextDiet));
e.printStackTrace();
}
return calories;
}
#Override
protected void onPostExecute(String calories) {
if (calories == "UNDEFINED") {
Toast.makeText(Diet.this, "Food not found", Toast.LENGTH_LONG).show();
} else {
editText=(findViewById(R.id.editTextDiet));
editText.setText(calories);
}
}
}
I have the following problem:
W/System.err: org.json.JSONException: No value for common
at org.json.JSONObject.get(JSONObject.java:392)
So the problem seems to be that the "common" array has no value, hence it cannot find it's length? I'm unsure as to why it cannot see the "common" array as i have looked at numerous other questions about getting Objects from Arrays and I have replicated the code identically each time but with the same result. If I use solely a JSONObject and ignore the full array I can see in the stacktrace that it is attempting to download the whole array into that object which means it's definitely not something wrong with the GET request or the API keys.
Thanks.
the error you are getting is because you aren't passing the String response to jsonObject so it can't find any thing in an empty object
the fix is
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject jsonRes = new JSONObject(inputString); \\this is the fix
JSONArray common = jsonRes.getJSONArray("common");
I have chat app where i need to develop user online state and for this i am calling API in every 15 seconds on server, which will return all logged in users and their online state in 0(Offline) and 1(Online).
I need to show whether user is online or offline (leaves app not logged out) while chatting.I have 1 array list which shows when app is launch with all logged in user id and their details including their online state and i created second API which return users online state in JSON.I have following option to achieve users online state
Replace existing array list item:-I am getting User ID and their online state in JSON but i need to run loop in every 15 second which replace values in existing arraylist
Store JSON in someway where i can easily find user id and its state:- If i store JSON in array list i need to run loop to find ID and its state which i dont want to,So which is best way to store JSON so i can easily get user state by its User ID.
Here is how i am getting JSON
protected List<WrapperClass> doInBackground(Void... params) {
userSession=new UserSession(context,"Elaxer");
UserState_Update=new ArrayList<>();
String data = null;
try {
String ID=userSession.getUserID(); //Getting Value from shared pref
data = URLEncoder.encode("User_ID", "UTF-8") + "=" + URLEncoder.encode(ID, "UTF-8");
Log.d(TAG,"Login ID "+ ID);
Log.d(TAG,"DO IN BACKGROUND START ");
URL url=new URL(URL_Path_NearBy);
connection= (HttpURLConnection) url.openConnection();
Log.d(TAG,connection.toString());
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
//For POST Only - Begin
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
os.close();
connection.connect();
InputStream inputStream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(inputStream));
Log.d(TAG,"GET INPUT STREAM AND PUUTING INTO READER");
String line;
StringBuffer stringBuffer=new StringBuffer();
while ((line=reader.readLine())!=null){
stringBuffer.append(line);
}
String completeJSON=stringBuffer.toString();
Log.d(TAG,"JSON ARRAY START");
JSONObject parentArray=new JSONObject(completeJSON);
JSONArray jsonArray=parentArray.getJSONArray("uData");
String LastSeen;
int LoginStatus,User_ID;
int Rec_Online_Status;
for (int i = 0; i <jsonArray.length() ; i++) {
JSONObject childObject=jsonArray.getJSONObject(i);
LastSeen=childObject.getString("lastseen") ;
LoginStatus=childObject.getInt("login_status") ;
User_ID=childObject.getInt("User_ID");
String UseID= String.valueOf(User_ID);
Log.d(TAG,"JSON Values "+LastSeen+" "+LoginStatus+" "+User_ID);
WrapperClass wrapperClass=new WrapperClass(UseID,LoginStatus);
UserState_Update.add(wrapperClass);
}
return UserState_Update; //List<WrapperClass> UserState_Update
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
This is the response as JSON
{
"status": "SUCCESS",
"uData": [
{
"User_ID": "4",
"login_status": "1",
"lastseen": "0000-00-00 00:00:00"
},
{
"User_ID": "1",
"login_status": "0",
"lastseen": "0000-00-00 00:00:00"
},
{
"User_ID": "12",
"login_status": "1",
"lastseen": "0000-00-00 00:00:00"
},
{
"User_ID": "33",
"login_status": "0",
"lastseen": "0000-00-00 00:00:00"
}
]
}
Is this right way to get user online state? (I know FCM is right way but FCM currently not ready on app server side)
UPDATE 2:-As code recommended by #XngPro i implement on doinBackground
Map<String,Online_Status_Wrapper.User> map=new HashMap<>();
Online_Status_Wrapper wrapper=gson.fromJson(completeJSON,Online_Status_Wrapper.class);
Log.d(TAG,"Wrapper Get Data value "+wrapper.getuData());
Log.d(TAG,"Wrapper Get Status value "+wrapper.getStatus());
for (Online_Status_Wrapper.User u: wrapper.getuData()){
map.put(u.getUser_ID(),u);
}
Log.d(TAG,"State of Other User users "+map.get(12).getLogin_status());//HERE I AM GETTING NullPointerException
return map;
I think you should use a Java serialization/deserialization library like Gson.
Hope to help you~
Example
private static void bar() {
String jsonStr = "{\"status\":\"SUCCESS\",\"uData\":[{\"User_ID\":\"4\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"1\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"12\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"33\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"}]}";
Gson gson = new Gson();
UserFoo userFoo = gson.fromJson(jsonStr, UserFoo.class);
Map<String, UserFoo.User> map = new HashMap<>();
for (UserFoo.User u : userFoo.getUData()) {
map.put(u.getUser_ID(), u);
}
System.out.println("userId: 12, loginState: " + map.get("12").getLogin_status());
}
public static class UserFoo {
/**
* status : SUCCESS
* uData : [{"User_ID":"4","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"1","login_status":"0","lastseen":"0000-00-00 00:00:00"},{"User_ID":"12","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"33","login_status":"0","lastseen":"0000-00-00 00:00:00"}]
*/
private String status;
private List<User> uData;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<User> getUData() {
return uData;
}
public void setUData(List<User> uData) {
this.uData = uData;
}
public static class User {
/**
* User_ID : 4
* login_status : 1
* lastseen : 0000-00-00 00:00:00
*/
private String User_ID;
private String login_status;
private String lastseen;
public String getUser_ID() {
return User_ID;
}
public void setUser_ID(String User_ID) {
this.User_ID = User_ID;
}
public String getLogin_status() {
return login_status;
}
public void setLogin_status(String login_status) {
this.login_status = login_status;
}
public String getLastseen() {
return lastseen;
}
public void setLastseen(String lastseen) {
this.lastseen = lastseen;
}
}
}
public class Test {
public static void main(String[] args) {
bar();
}
private static void bar() {
String jsonStr = "{\"status\":\"SUCCESS\",\"uData\":[{\"User_ID\":\"4\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"1\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"12\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"33\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"}]}";
Gson gson = new Gson();
UserFoo userFoo = gson.fromJson(jsonStr, UserFoo.class);
Map<String, UserFoo.User> map = new HashMap<>();
for (UserFoo.User u : userFoo.getUData()) {
map.put(u.getUser_ID(), u);
}
System.out.println("userId: " + "12, loginState: " + map.get("12").getLogin_status());
}
public static class UserFoo {
/**
* status : SUCCESS
* uData : [{"User_ID":"4","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"1","login_status":"0","lastseen":"0000-00-00 00:00:00"},{"User_ID":"12","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"33","login_status":"0","lastseen":"0000-00-00 00:00:00"}]
*/
private String status;
private List<User> uData;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<User> getUData() {
return uData;
}
public void setUData(List<User> uData) {
this.uData = uData;
}
public static class User {
/**
* User_ID : 4
* login_status : 1
* lastseen : 0000-00-00 00:00:00
*/
private String User_ID;
private String login_status;
private String lastseen;
public String getUser_ID() {
return User_ID;
}
public void setUser_ID(String User_ID) {
this.User_ID = User_ID;
}
public String getLogin_status() {
return login_status;
}
public void setLogin_status(String login_status) {
this.login_status = login_status;
}
public String getLastseen() {
return lastseen;
}
public void setLastseen(String lastseen) {
this.lastseen = lastseen;
}
}
}
}
Print
im trying to have my app connect to a rest API and pull the data from it. Ive so far pulled the data . but i dont know how to parse it. i believe thats what you do next.
here a snippet of my code that conencts to my rest API and gets the data . the error i get is JSONArray cannot be converted to JSONObject
if (status == 200) {
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String responseString;
StringBuilder sb = new StringBuilder();
while ((responseString = reader.readLine()) != null) {
sb = sb.append(responseString);
}
String speciesListData = sb.toString();
species= SpeciesJson.fromJson(speciesListData);
Log.d(Constants.TAG, "speciesJSON: " + species);
return true;
}
this is were i tried to parse it , it was working fine up until here. hers is the line were i try to parse it
species= SpeciesJson.fromJson(speciesListData);
and this thats were it broke lol
public class SpeciesJson {
private String scientific_name, name,description;
public SpeciesJson (JSONObject species) throws JSONException {
this.scientific_name=species.optString("scientific_name");
this.name=species.optString("name");
this.description=species.optString("description");
}
public static ArrayList<SpeciesJson> fromJson(String photoData) throws JSONException {
ArrayList<SpeciesJson> speciesData = new ArrayList<>();
JSONObject data = new JSONObject(photoData);
JSONObject photos = data.optJSONObject("name");
JSONArray photoArray = photos.optJSONArray("name");
for (int i = 0; i < photoArray.length(); i++) {
JSONObject photo = (JSONObject) photoArray.get(i);
SpeciesJson currentPhoto = new SpeciesJson(photo);
speciesData.add(currentPhoto);
}
return speciesData;
}
so when i run it using the parsing method i made, it doesnt not work.
the sample of hte json data is below, im trying to show the scientific_name and name in a view
{
"id": 1,
"scientific_name": "Platanus racemosa",
"name": "California Sycamore",
"description": "typically in river areas, but planted all throughout L.A",
"type": 1
},
{
"id": 2,
"scientific_name": "Pyrus kawakamii",
"name": "Ornamental Pear",
"description": "native to Asia, commonly planted in L.A",
"type": 1
},
{
"id": 3,
"scientific_name": "Liquidambar styraciflua",
"name": "American Sweetgum",
"description": "native to SE U.S, planted all around L.A",
"type": 1
},
{
"id": 4,
"scientific_name": "Setophaga coronata",
"name": "Yellow-rumped Warbler",
"description": "native bird, spends the winter in L.A before migrating north during the summer to breed",
"type": 2
},
{
"id": 5,
"scientific_name": "Calypte anna",
"name": "Anna's Hummingbird",
"description": "native bird, does not migrate. Spends the year in L.A",
"type": 2
},
{
"id": 6,
"scientific_name": "Regulus calendula",
"name": "Ruby-crowned Kinglet",
"description": "native bird, spends the winter in L.A before migrating north during the summer to breed",
"type": 2
}
]
My Dear Friend Use googles GSON Library that's it.
And For Your Help I made this little bit easier.
Make This Class SpeciesJson.java
public class SpeciesJson {
private String scientific_name;
private String name;
private String description;
public SpeciesJson() {
}
public SpeciesJson(String scientific_name,String name,String description) {
this.scientific_name = scientific_name;
this.name = name;
this.description = description;
}
//And getter,setters
}
If SpeciesJson Is simple an object then use this
Gson gson = new Gson();
SpeciesJson species = gson.fromJson(responseString,SpeciesJson.class);
If SpeciesJson Is an ArrayList then use this (Its Looks Like Your Case So Check This As Your Json Response Consist Multiple SpeciesJson Objects)
Gson gson = new Gson();
ArrayList<SpeciesJson> species = new ArrayList<>();
SpeciesJson[] speciesarray = (SpeciesJson[]) gson.fromJson(responseString,SpeciesJson[].class);
Collections.addAll(species, speciesarray);
And If You wanna learn something more about Gson Library check this link
https://guides.codepath.com/android/Leveraging-the-Gson-Library
Well you can use GSON to parse the data and Volley to get the data.
//Create volley request
String url = String.format("SOME_URL", arrayOfObject);
RequestQueue queue = VolleyService.getInstance(this.getContext()).getRequestQueue();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// we got the response, now our job is to handle it
try {
ArrayList<SpeciesJson> speciesData = getDataFromJson(stream);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//something happened, treat the error.
Log.e("Error", error.toString());
}
});
queue.add(request);
//If your JSON data is an Array
private static List<SpeciesJson> getDataFromJson(String json) {
Gson gson = new GsonBuilder().create();
List<SpeciesJson> result = new ArrayList<>();
try {
JSONObject posts=new JSONObject(json);
JSONArray dataArray=posts.getJSONArray("data");
for(int n = 0; n < dataArray.length(); n++)
{
JSONObject object = dataArray.getJSONObject(n);
result.add(gson.fromJson(object.toString(), SpeciesJson.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
And volley Service
public class VolleyService {
private static VolleyService instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private VolleyService(Context context) {
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url,bitmap);
}
});
}
public static VolleyService getInstance(Context context) {
if (instance == null) {
instance = new VolleyService(context);
}
return instance;
}
public RequestQueue getRequestQueue() {
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
Or you can use Retrofit library to parse it for you:
http://www.vogella.com/tutorials/Retrofit/article.html
https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit
You should use retrofit library with GsonConverterFactory. The best solution to manage network response.
I develop an Android application and I have to deserialize a JSON file.
I have these classes:
public class Medicine {
#SerializedName("substanta_activa")
private List<String> active_substance;
#SerializedName("produse")
private List<Product> product;
#SerializedName("dozaj")
private Dosage dosage;
#SerializedName("mentiuni")
private List<String> notes;
#SerializedName("cuvinte_cheie")
private List<String> keyword;
/* + getters and setters */
}
public class Product {
#SerializedName("denumire_comerciala")
private String productName;
#SerializedName("forme_de_prezentare")
private List<String> form;
/* + getters and setters */
}
public class Dosage {
#SerializedName("nounascuti")
private String newborn;
#SerializedName("copii")
private String child;
#SerializedName("adulti")
private String adult;
/* + getters and setters */
}
And I have the following JSON file:
[
{
"substanta_activa": [
"trimebutinum"
],
"produse": [
{
"denumire_comerciala": "Debridat",
"forme_de_prezentare": [
"susp. buvabilă",
"susp. 24mg/5ml în flac 250ml",
"compr 100mg"
]
},
{
"denumire_comerciala": "Ibutin",
"forme_de_prezentare": [
"compr 300mg"
]
},
{
"denumire_comerciala": "Trimebutin",
"forme_de_prezentare": [
"compr 100mg"
]
},
{
"denumire_comerciala": "Colperin",
"forme_de_prezentare": [
"compr 100mg"
]
}
],
"dozaj": {
"nounascuti": "1ml/kg/zi div 3,",
"copii": "1ml/kg/zi div 3, peste 5 ani 3x10ml",
"adulti": "3x1-2 compr/zi, 1x300mg/zi sau 3x1-2 lingură/zi"
},
"mentiuni": [
"se poate administra de la naștere",
"se poate administra amestecat cu apă, lapte",
"10ml conține 6g zahăr"
],
"cuvinte_cheie": [
"gastro",
"colică",
"dureri abdominale funcționale",
"constipație"
]
},
{
"substanta_activa": [
"benzydaminum"
],
"produse": [
{
"denumire_comerciala": "Tantum Verde comprimate",
"forme_de_prezentare": [
"pastile pt supt 3mg"
]
},
{
"denumire_comerciala": "Tantum Verde spray",
"forme_de_prezentare": [
"spray bucofaringian 0,15%, 0,3%"
]
}
],
"dozaj": {
"nounascuti": "contraindicat",
"copii": "2-6 ani: 2-6x1 puf/4kg; >6 sni: 2-6x 4doze sau 3x1 pastila/zi",
"adulti": "2-6x 4puf sau 3x1 pastila/zi"
},
"mentiuni": [
"se admin. max. 7 zile"
],
"cuvinte_cheie": [
"antiseptic, anestezic, antiinflamator, oral, OTC"
]
}
]
I have tried several ways, with GSON and without it as well but with no success. Thank you for your help in advance.
EDIT
A little bit more detail:
I have a MainPageActivity, where I initialize an Inputstream, set a path and call my deserialize method from JSONParser class:
InputStream is = null;
String internalStoragePath = getApplicationContext().getFilesDir().getAbsolutePath();
File fileToInternalStorage = new File(internalStoragePath + "/medicinelist.json");
try {
is = new FileInputStream(fileToInternalStorage);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (is == null) {
is = getResources().openRawResource(R.raw.gyogyszerek);
}
jsonParser = new JSONParser();
try {
medicines = jsonParser.readJsonStream(getApplicationContext(), is);
//medicines = jsonParser.jsonDeserializer(getApplicationContext(), is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
In my JSONParser class, as I have mentioned I have tried several ways to deserialize the JSON input.
Here is the "traditional" way, with Android's built-in JsonReader class (sorry, a little bit long):
public ArrayList readJsonStream(Context applicationContext, InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
try {
return readMedicineArray(reader);
} finally {
reader.close();
}
}
public ArrayList readMedicineArray(JsonReader reader) throws IOException {
ArrayList medicines = new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
medicines.add(readMedicine(reader));
}
reader.endArray();
return medicines;
}
public Medicine readMedicine(JsonReader reader) throws IOException {
List active_substance = null;
List product = null;
Dosage dosage = null;
List notes = null;
List keyword = null;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("substanta_activa")) {
active_substance = readActiveSubstanceArray(reader);
} else if (name.equals("produse")) {
product = readProductArray(reader);
} else if (name.equals("dozaj")) {
dosage = readDosage (reader);
} else if (name.equals("mentiuni") && reader.peek() != JsonToken.NULL) {
notes= readNotesArray(reader);
} else if (name.equals("cuvinte_cheie") && reader.peek() != JsonToken.NULL) {
keyword = readKeywordArray(reader);
} else {
reader.skipValue();
}
}
reader.endObject();
return new Medicine(active_substance, product, dosage, notes, keyword);
}
public List readActiveSubstanceArray(JsonReader reader) throws IOException {
List active_substance = new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
active_substance.add(reader.nextString());
}
reader.endArray();
return active_substance;
}
public List readProductArray(JsonReader reader) throws IOException {
List product = new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
product.add(readProduct(reader));
}
reader.endArray();
return product;
}
public Product readProduct(JsonReader reader) throws IOException {
String productName = null;
List form = null;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("denumire_comerciala")) {
productName = reader.nextString();
} else if (name.equals("forme_de_prezentare")) {
form = readFormArray(reader);
} else {
reader.skipValue();
}
}
reader.endObject();
return new Product(productName, form);
}
public List readFormArray(JsonReader reader) throws IOException {
List form = new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
form.add(reader.nextString());
}
reader.endArray();
return form;
}
public Dosage readDosage(JsonReader reader) throws IOException {
String newborn= null;
String child= null;
String adult= null;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("nounascuti")) {
newborn= reader.nextString();
} else if (name.equals("copii")) {
child= reader.nextString();
} else if (name.equals("adulti")) {
adult= reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
return new Dosage(newborn, child, adult);
}
public List readNotesArray(JsonReader reader) throws IOException {
List notes= new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
notes.add(reader.nextString());
}
reader.endArray();
return notes;
}
public List readKeywordArray(JsonReader reader) throws IOException {
List keyword= new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
keyword.add(reader.nextString());
}
reader.endArray();
return keyword;
}
And here is the other way with GSON library:
public ArrayList<Medicine> jsonDeserializer(Context contexts, InputStream in) throws IOException {
Reader reader = new InputStreamReader(in);
ArrayList medicinesList = new ArrayList();
final GsonBuilder gsonBuilder = new GsonBuilder();
final Gson gson = gsonBuilder.create();
Medicine[] medicinesArray = new Gson().fromJson(reader, Medicine[].class);
for(int i = 0; i < medicinesArray.length; ++i){
medicinesList.add(medicinesArray[i]);
}
return medicinesList;
}
None of them works, but I don't know what is the problem.
//try this
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Medicine>>() {}.getType();
List<Medicine> medList = gson.fromJson(<YOUR JSON STRING>, listType);
1) Firstly create your classes like this:
public class Produse
{
public String Denumire_comerciala;
public List<String > Forme_de_prezentare;
}
public class Dosage
{
public String Nounascuti;
public String Copii;
public String Adulti;
}
public class RootObject
{
public List<String > Substanta_activa;
public List<Produse> Produse;
public Dosage Dozaj;
public List<String > Mentiuni;
public List<String > Cuvinte_cheie;
}
2) Then use gson like in this way:
Gson _gson = new GsonBuilder().create();
RootObject root= gson.fromJson("*YOUR JSON HERE*", RootObject .class);
Hope it will help.
use this method:
public static <T> T JsonParse(T t, String response)
throws JsonSyntaxException, IOException, XmlPullParserException {
InputStream in = new ByteArrayInputStream(response.getBytes());
JsonReader reader;
reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
GsonBuilder b = new GsonBuilder();
Gson gson = b.create();
t = (T) gson.fromJson(reader, t.getClass());
reader.close();
return t;
}
use this method:
ArrayList<Medicine> arrlist=JsonParse(new Medicine(),JsonResponse);
i hope its useful to you.
I was a novice at the json parsing from url. yesterday I've tried parsing json simple data. Now I am confused to form a json parsing the data as below. I still can not how to parse arrays and objects in json. Please help me guys ..
here my MainActivity.java
public class MainActivity extends ListActivity {
/** Called when the activity is first created. */
private static String URL = "http://api.themoviedb.org/3/genre/18/movies?api_key=d397dd2d354f088c6f0eb91c6b160bb0";
// tag
private static final String TAG_ID = "id";
private static final String TAG_page = "page";
private static final String TAG_results = "results";
private static final String TAG_backdrop_path = "backdrop_path";
private static final String TAG_id = "id";
private static final String TAG_original_title = "original_title";
private static final String TAG_release_date = "release_date";
private static final String TAG_poster_path = "poster_path";
private static final String TAG_title = "title";
private static final String TAG_vote_average = "vote_average";
private static final String TAG_vote_count = "vote_count";
private static final String TAG_total_pages = "total_pages";
private static final String TAG_total_results = "total_results";
JSONArray results = null;
JSONArray id = null;
JSONArray page = null;
JSONArray pages = null;
JSONArray tot_result = null;
// panggil class parser
JSONparser parser = new JSONparser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> genreList = new ArrayList<HashMap<String, String>>();
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getJSONArray(TAG_ID);
page = json.getJSONArray(TAG_page);
pages = json.getJSONArray(TAG_total_pages);
tot_result = json.getJSONArray(TAG_total_results);
for (int i = 0; i < results.length(); i++) {
JSONObject data = results.getJSONObject(i);
String backdrop = data.getString(TAG_backdrop_path);
String idd = data.getString(TAG_id).toString();
String ori = data.getString(TAG_original_title);
String releas = data.getString(TAG_release_date);
String poster = data.getString(TAG_poster_path);
String title = data.getString(TAG_title);
String average = data.getString(TAG_vote_average);
String count = data.getString(TAG_vote_count);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_backdrop_path, backdrop);
map.put(TAG_ID, idd);
map.put(TAG_original_title, ori);
map.put(TAG_release_date, releas);
map.put(TAG_poster_path, poster);
map.put(TAG_title, title);
map.put(TAG_vote_average, average);
map.put(TAG_vote_count, count);
genreList.add(map);
}
// Sort by
/*********************************
* Collections.sort(genreList, new Comparator<HashMap<String,
* String>>() {
*
* #Override public int compare(HashMap<String, String> a,
* HashMap<String, String> b) { return
* a.get(TAG_NAMA).compareTo(b.get(TAG_ID)); } });
******************************/
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
// tampilkan ke listadapter
ListAdapter adapter = new SimpleAdapter(this, genreList,
R.layout.list_data, new String[] { TAG_ID, TAG_page,
TAG_results, TAG_backdrop_path, TAG_id,
TAG_original_title, TAG_release_date, TAG_poster_path,
TAG_title, TAG_vote_average, TAG_vote_count,
TAG_total_pages, TAG_total_results }, new int[] {
R.id.id, R.id.page, R.id.result, R.id.backdrop_path,
R.id.idd, R.id.original_title, R.id.release_date,
R.id.poster_path, R.id.title, R.id.vote_average,
R.id.vote_count, R.id.total_pages, R.id.total_results });
setListAdapter(adapter);
}
}
here my JSONparser.java
public class JSONparser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONparser() {
}
public JSONObject getJSONFromUrl(String url) {
// http request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
// TODO: handle exception
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("BUffer Error", "Error converting result" + e.toString());
}
// try parse string to a json
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
// TODO: handle exception
Log.e("Json parser", "error parsing data" + e.toString());
}
return jObj;
}
}
here my json data.
{
"id": 18,
"page": 1,
"results": [
{
"backdrop_path": "/6xKCYgH16UuwEGAyroLU6p8HLIn.jpg",
"id": 238,
"original_title": "The Godfather",
"release_date": "1972-03-24",
"poster_path": "/d4KNaTrltq6bpkFS01pYtyXa09m.jpg",
"title": "The Godfather",
"vote_average": 9.1999999999999993,
"vote_count": 125
},
{
"backdrop_path": "/ooqPNPS2WdBH7DgIF4em9e0nEld.jpg",
"id": 857,
"original_title": "Saving Private Ryan",
"release_date": "1998-07-24",
"poster_path": "/35CMz4t7PuUiQqt5h4u5nbrXZlF.jpg",
"title": "Saving Private Ryan",
"vote_average": 8.9000000000000004,
"vote_count": 83
}
],
"total_pages": 25,
"total_results": 499
}
JSONObject jObject_Main= new JSONObject(jsonstring);
//get json simple string
String id = jObject_Main.getString("id");
String page = jObject_Main.getString("page");
//get json Array and parse it.
JSONArray jsonArray = jObject_Main
.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String backdrop_path=jsonObject.getString("backdrop_path");
}
i hope its useful to you.
please change this in your code:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString("id");
page = json.getString("page");
tot_result = json.getJSONArray(results);
i hope you understand it.
Try this..
In your Global:
JSONArray results = null;
String id = null;
String page = null;
String pages = null;
String tot_result = null;
Inside Try Catch:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString(TAG_ID); // Changes here
page = json.getString(TAG_page); // Changes here
pages = json.getString(TAG_total_pages); // Changes here
tot_result = json.getString(TAG_total_results); // Changes here
results = json.getJSONArray(TAG_results); // Add this line
for (int i = 0; i < results.length(); i++) {
// Remaining all correct
}
EDIT:
new DownloadImageTask()
.execute("your image url");
}
and DownloadImageTask.class
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
imageview.setImageBitmap(result);
}
}
Your JSON is JSONObject and it contains JSONArray
Parse Object
Parse Array
Example:
JSONObject jsonObj = new JSONObject(your_json_string);
String id = jsonObj.getString("id");
String page = jsonObj.getString("page"); // or getInt("page");
JSONArray results = jsonObj.getJSONArray("results");
int len = results.length(); // length or size, I don't remember, you can check it
for (int i = 0; i < len; i++) {
JSONObject obj = results.getJSONObject(i);
String backdropPath = obj.getString("backdrop_path");
// ...
}
you need add " results= json.getJSONArray(TAG_results);" below
"tot_result = json.getJSONArray(TAG_total_results);"