I am new to Android and JAVA and I am trying to parse a json response. I know how to parse jsonarray but no Idea how to parse jsonobject. Can someone tell me how? Below is my Response.
{"118":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"},"119":{"garment_color":"hjsadjjs","garment_name":"sdasd","garment_price":"23478"}}
And this is how parsed jsonarray.
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.INVISIBLE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
//GetDataAdapter2.setImageServerLarger(json.getString(JSON_IMAGE_LARGER));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
GetDataAdapter2.setMrp_price(json.getString(JSON_MRP_PRICE));
GetDataAdapter2.setDisc_price(json.getString(JSON_DISC_PRICE));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
Please Someone help. Thanks.
In my opinion, use Gson library, where you give it the json object/array/string and it automatically parses it into a java object. Note that you have to define the java class with the appropriate fields.
EDIT: So here's an answer that goes with the suggested guidelines:
First create your model classes just like you will receive them from the server:
public class MyServerObject {
MyGarment jsonKeyName;
}
public class MyGarment {
String garment_color;
String garment_name;
String garment_price;
}
Next, after receiving your json string, parse it using Gson:
Gson gson = new Gson();
String json= "{"jsonKeyName":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"};
MyServerObject serverObject = gson.fromJson(json, MyServerObject.class);
Now, you can access your Garment object from your server object with all the values parsed correctly. Also note that if you're receiving a json array you could add the object as a list in your MyServerObject.class.
Hope this helps.
as per my above comment
you need to make JSONObject request instead of JSONArray request
try this to parse your JSON Response
try {
JSONObject jsonObject= new JSONObject("Response");
JSONObject jsonObject1=jsonObject.getJSONObject("118");
String garment_color=jsonObject1.getString("garment_color");
String garment_name=jsonObject1.getString("garment_name");
String garment_price=jsonObject1.getString("garment_price");
JSONObject jsonObject2=jsonObject.getJSONObject("119");
String garment_color2=jsonObject1.getString("garment_color");
String garment_name2=jsonObject1.getString("garment_name");
String garment_price2=jsonObject1.getString("garment_price");
} catch (JSONException e) {
e.printStackTrace();
}
Use StringRequest instead of JSONObject/JSONArray request and finally fetch value like this:
JSONObject object = new JSONObject(YOUR JSON RESPONSE);
String s1 = object.getJSONObject("118").getString("garment_color");
Related
when there is only one object, i dont have problem to retrieve variable from database
but when i want to retrive variable from only user1 or user2 the text in android doesnt appear anything.
this is my array from php code
{"users":[{"id":"5","name":"user1","updated_at":"2020-10-21 13:35:10"},{"id":"6","name":"user2","updated_at":"2020-10-21 11:29:53"}]}
and this my java code
private void getData(String name) {
String tag_string_req = "get";
ArrayList<HashMap<String, String>> list_data;
list_data = new ArrayList<HashMap<String, String>>();
StringRequest strReq = new StringRequest(Method.GET,
AppConfig.URL_GET, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("users");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
String pengguna = jsonObject.getString("name");
if (pengguna.contains(name)) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("updated_at", json.getString("updated_at"));
list_data.add(map);
}
update_time.setText(list_data.get(0).get("updated_at"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
});
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
my question is how to get specific JSON object based on some variable? so the text in android only show text based on user.
edit : the problem already solved by some edit in php code, so only the object fetching from database based on user.
my response in android
{"users":[{"id":"6","name":"user2","updated_at":"2020-10-21 13:35:10"}]}
the problem right now is the textview doesnt show me the value although the response already correct
You can look up to follow this :
JSONObject jsonObject = new JSONObject();
jsonObject.getJSONObject("key");
It will resolve your problem, I think.
I'm parsing a simple JSON response, and it is working when trying to parse the employer name, but it gets to a point where it will eventually crash and say that my 'review' json object, is empty. Here is the response:
https://raw.githubusercontent.com/vikrama/feed-json-sample/master/feed.json
And here is how I'm reading it:
private void extractName()
{
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest request = new JsonObjectRequest(JSON_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject gimme = response.getJSONObject("response");
JSONArray resultsArray = gimme.getJSONArray("results");
for(int i = 0; i < resultsArray.length(); i++)
{
JSONObject info = resultsArray.getJSONObject(i);
JSONObject review = info.getJSONObject("review");
Log.d("COMP NAME", review.getString("employerName"));
companyNames.add(review.getString("employerName"));
}
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
adapter = new CompanyAdapter(MainActivity.this, companyNames);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage());
}
});
queue.add(request);
}
The debug line prints the correct values, then abruptly stops saying "no value for review". I'm pretty confused by this because it seems i'm reading through the data correctly. (use https://jsonformatter.org/json-viewer to better format this json i listed above)
Also, everything else in my recyclerview is set up properly, and the method extractName() is being called in the onCreate() method of my main activity.
This is happening because in some JSON Object you don't have "review" object, so it's throwing your code directly to catch Exception.
In order to overcome this, Please use:-
if(info.has("review")) {
JSONObject review = info.getJSONObject("review");
companyNames.add(review.getString("employerName"));
}
Instead of:
JSONObject review = info.getJSONObject("review");
Log.d("COMP NAME", review.getString("employerName"));
companyNames.add(review.getString("employerName"));
I am developing a java application in android studio and a Rest web server in java, netbeans.
I need to send a JSON to the server ...
I did the whole engine the webService and tested it using Postman.
The Json used was this:
{
"id":0,
"ticket":"2132158645161654561651616",
"avaliacoes":[
{
"idAvaliacao":1,
"nota":5,
"observacao":"testeTEste"
},
{
"idAvaliacao":2,
"nota":4,
"observacao":"testeTEste"
}
]
}
Worked perfectly.
So I went to generate Json dynamically in the application:
public void enviaDadosVenda(){
JSONObject obj = new JSONObject();
JSONArray avaliacoes = new JSONArray();
JSONObject avaliacao;
try {
obj.put("id", 0);
obj.put("ticket", PrincipalActivity.ticket_id);
for(int i=0; i < PrincipalActivity.listAval.size();i++){
avaliacao = new JSONObject();
avaliacao.put("idAvaliacao", listAval.get(i).getId());
avaliacao.put("nota", listAval.get(i).getNota());
avaliacao.put("observacao", listAval.get(i).getObservacoes());
avaliacoes.add(avaliacao);
}
obj.put("avaliacoes", avaliacoes);
} catch (JSONException e) {
e.printStackTrace();
}
}
The generated Json is this:
{
"id":0,
"ticket":"2132158645161654561651616",
"avaliacoes":"[
{
\"idAvaliacao\":1,
\"nota\":5,
\"observacao\":\"testeTEste\"
},
{
\"idAvaliacao\":2,
\"nota\":4,\"observacao\":\"testeTEste\"
}
]"
}
If I use this second Json on Postman the webService no gets it correctly.
Get the id and the ticket, but the evaluations array gets a single item(avaliacoes.get(0)) = null.
I've looked at other posts about Json and ArrayJsons and nothing helped me ...
Parsing JSON Object in Java
Convert JsonObject to String
How to create correct JSONArray in Java using JSONObject
https://pt.stackoverflow.com/questions/140442/reconhecer-um-jsonobject-ou-jsonarray
Just replace avaliacoes.add(avaliacao); with avaliacoes.put(avaliacao);
public void enviaDadosVenda(){
JSONObject obj = new JSONObject();
JSONArray avaliacoes = new JSONArray();
JSONObject avaliacao;
try {
obj.put("id", 0);
obj.put("ticket", "DemoActivity.ticket_id");
for(int i=0; i < 2;i++){
avaliacao = new JSONObject();
avaliacao.put("idAvaliacao", "1");
avaliacao.put("nota", "nota");
avaliacao.put("observacao", "observacao");
avaliacoes.put(avaliacao);
}
obj.put("avaliacoes", avaliacoes);
Log.d("DEMO", obj.toString()); // {"id":0,"ticket":"DemoActivity.ticket_id","avaliacoes":[{"idAvaliacao":"1","nota":"nota","observacao":"observacao"},{"idAvaliacao":"1","nota":"nota","observacao":"observacao"}]}
} catch (JSONException e) {
e.printStackTrace();
}
}
For best practice use Gson
I want to retrieve comments from a Flickr photo in my Android app, and have created a JSONObjectRequest using the following code:
public void loadComments(ImageInfo photo) {
//clear the comments arraylist ready for new request
NetworkMgr.getInstance(this).commentsList.clear();
NetworkMgr netMgr = NetworkMgr.getInstance(getApplicationContext());
RequestQueue requestQueue = netMgr.requestQueue;
String id = photo.id;
String url = "https://api.flickr.com/services/rest/?method=flickr.photos.comments.getList&api_key=MY_API_KEY&format=json&nojsoncallback=1&extras=authorname,_content&photo_id=" + id;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, responseListener, errorListener);
requestQueue.add(request);
adapter.notifyDataSetChanged();
}
The photo ID is correctly being retrieved and appended to the String url, and below I use a response listener to get authorname and _content, from each comment object:
private Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject comments = response.getJSONObject("comments");
JSONArray commentList = comments.getJSONArray("comment");
for (int i = 0; i < commentList.length(); i++) {
ImageInfo newComment = new ImageInfo();
JSONObject comment = commentList.getJSONObject(i);
newComment.authorname = comment.getString("authorname");
newComment.commentContent = comment.getString("_content");
//add data to arraylist
NetworkMgr.getInstance(DetailsActivity.this).commentsList.add(newComment);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
adapter.notifyDataSetChanged();
}
};
private Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
};
However when I put this url in my browser to view the JSON data, the comment JSONObject is non-existent.
How The JSON Response Should Look <<<< How My JSON Response Looks <<<<
Does anybody know why I cannot retrieve the JSON comment object and its data?
Try this
Put this in your loop
JSONObject allvaluesJsonObject=new JSONObject();
allvaluesJsonObject=jsonArray.getJSONObject(i);
remove this ImageInfo newComment = new ImageInfo();
I have json data format like
{
"status":200,
"message":"ok",
"response": {"result":1, "time": 0.0123, "values":[1,1,0,0,0,0,0,0,0]
}
}
I want to get one value of values array and put it on textView in eclipse. Look my code in eclipse
protected void onPostExecute (String result){
try {
JSONobject json = new JSONObject(result);
tv.setText(json.toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}
You can use GSON
Create a POJO for your response
public class Response{
private int result;
private double time;
private ArrayList<Integer> values;
// create SET's and GET's
}
And then use GSON to create the object you desire.
protected void onPostExecute (String result){
try {
Gson gson = new GsonBuilder().create();
Response p = gson.fromJson(result, Response.class);
tv.setText(p.getValues());
}catch (JSONException e){
e.printStackTrace();
}
}
You can use jackson library for json parsing.
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readTree(json);
map.get("key");
You can use readTree if you know json is an instance of JSONObject class else use typeref and go with readValue to get the map.
protected void onPostExecute (String result){
try {
JSONObject json = new JSONObject(result);
JSONObject resp = json.getJSONObject("response");
JSONArray jarr = resp.getJSONArray("values");
tv.setText(jarr.get(0).toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}