I have a following json object, I could able to get plistDate, and pcategory, but I wonder how to parse each image object in the following json.
here is what I have so far
obj = new JSONObject(jsonObject);
listImages = obj.optString("images");
jsonObject
{
"plistDate": "2016-02-19 22:02:41",
"pcategory": "Kategori seciniz",
"images": {
"pimagePath": "products/138_1455940961.jpg",
"pimagePath2": "products/138_1455940961_2.jpg",
"pimagePath3": "products/138_1455940961_3.jpg",
"pimagePath4": "products/138_1455940961_4.jpg",
"pimagePath5": "products/138_1455940961_5.jpg"
}
}
images is inner object so you would have to retrieve it like that
JSONObject obj = new JSONObject("you jsin String");
String pcategory = obj.getString("pcategory");
String plistDate = obj.getString("plistDate");
JSONObject images_JsonObject = obj.getJSONObject("images");
String pimagePath = images_JsonObject.getString("pimagePath");
String pimagePath2 = images_JsonObject.getString("pimagePath2");
String pimagePath3 = images_JsonObject.getString("pimagePath3");
String pimagePath4 = images_JsonObject.getString("pimagePath4");
String pimagePath5 = images_JsonObject.getString("pimagePath5");
Update
JSONObject images_JsonObject = obj.getJSONObject("images");
Iterator<String> stringIterable = images_JsonObject.keys();
HashMap<String, String> hashMap = new HashMap<>();
ArrayList<String> list = new ArrayList<>();
while (stringIterable.hasNext()){
String key = stringIterable.next();
hashMap.put(key, images_JsonObject.getString(key));
list.add(images_JsonObject.getString(key));
}
Related
the JSON data from the API I'm using
Part of the code: I've indicated in the code, but I'm not sure what to put:
JSONObject volumeObj = itemsObj.getJSONObject(""); inside the " " based on that API. What can I modify in the code or put in the " " to let me get the objects from the {0}, {1} etc etc?
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
// below line is use to make json object request inside that we
// are passing url, get method and getting json object. .
JsonObjectRequest booksObjrequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressBar.setVisibility(View.GONE);
// inside on response method we are extracting all our json data.
try {
JSONArray itemsArray = response.getJSONArray("result");
for (int i = 0; i < itemsArray.length(); i++) {
JSONObject itemsObj = itemsArray.getJSONObject(i);
**JSONObject volumeObj = itemsObj.getJSONObject("");**
String title = volumeObj.optString("title");
String subtitle = volumeObj.optString("subtitle");
JSONArray authorsArray = volumeObj.getJSONArray("authors");
String publisher = volumeObj.optString("publisher");
String publishedDate = volumeObj.optString("publishedDate");
String description = volumeObj.optString("description");
Did you want to obtain the items of the array? The "result" array contains these objects, so you can just access them with indices:
for (int i = 0; i < itemsArray.length(); i++) {
/* This is the ith object in the array */
JSONObject volumeObj = itemsArray.getJSONObject(i);
String title = volumeObj.optString("title");
String subtitle = volumeObj.optString("subtitle");
JSONArray authorsArray = volumeObj.getJSONArray("authors");
String publisher = volumeObj.optString("publisher");
String publishedDate = volumeObj.optString("publishedDate");
String description = volumeObj.optString("description");
...
}
Currently I'm trying to display JSON data (hosted on a Webserver) in a ListView in Android. The App correctly receives the data but is unable to process it further to display it in said ListView.
The error is as follows:
JSON parsing error: Value ... of type org.json.JSONArray cannot be converted to JSONObject
The JSON data I'm trying to parse looks like the following:
[{"idBuch":1,"autor":"Erich Maria Remarque","name":"Im Westen nichts Neues","preis":20,"buchtyp":{"idBuchtyp":3,"typenamen":"Geschichte"}}]
The code that processes the received JSON-String:
try{
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray books = jsonObject.getJSONArray("book");
for(int i = 0; i < books.length(); i++){
JSONObject obj = books.getJSONObject(i);
String idBook = obj.getString("idBuch");
String author = obj.getString("autor");
String name = obj.getString("name");
String price = obj.getString("preis");
JSONObject booktype = obj.getJSONObject("buchtyp");
String idBooktype = booktype.getString("idBuchtyp");
String typename = booktype.getString("typenamen");
HashMap<String, String> book = new HashMap<>();
book.put("idBook", idBook);
book.put("author", author);
book.put("name", name);
book.put("price", price);
book.put("genre", typename);
bookList.add(book);
} }catch(final JSONException e)
I am aware of the fact that there are a lot of similar questions on this site but I still had no success regarding this issue. Thank you in advance.
The JSON that you provided only contains an array.
[
{
"idBuch": 1,
"autor": "Erich Maria Remarque",
"name": "Im Westen nichts Neues",
"preis": 20,
"buchtyp": {
"idBuchtyp": 3,
"typenamen": "Geschichte"
}
}
]
However, your code expects the root to be an object with field book.
{
"book": [
{
"idBuch": 1,
"autor": "Erich Maria Remarque",
"name": "Im Westen nichts Neues",
"preis": 20,
"buchtyp": {
"idBuchtyp": 3,
"typenamen": "Geschichte"
}
}
]
}
In this case, try replacing the line:
JSONObject jsonObject = new JSONObject(jsonStr);
with
JSONArray books = new JSONArray(jsonStr);
and proceed as normal. Your end result should look like:
try {
JSONArray books = new JSONArray(jsonStr);
for (int i = 0; i < books.length(); i++) {
JSONObject obj = books.getJSONObject(i);
String idBook = obj.getString("idBuch");
String author = obj.getString("autor");
String name = obj.getString("name");
String price = obj.getString("preis");
JSONObject booktype = obj.getJSONObject("buchtyp");
String idBooktype = booktype.getString("idBuchtyp");
String typename = booktype.getString("typenamen");
HashMap < String, String > book = new HashMap < > ();
book.put("idBook", idBook);
book.put("author", author);
book.put("name", name);
book.put("price", price);
book.put("genre", typename);
bookList.add(book);
}
} catch (final JSONException e) {
e.printStackTrace()
}
In my application I am receiving a JSON object as
{"secQueList":{"1":"Which is your favorite book?","2":"Who was your childhood hero?","3":"What is your pet's name?","4":"What make was your first car or bike?","5":"What is your favorite color?","6":"Which is your favorite sports team?","7":"What was the name of your school?","8":"What is your mother's maiden name?","9":"Which is your birthplace?","10":"Which is your favourite sport?","11":"Which is your favourite place of visit?"},"que1":null,"ans1":null,"message":null,"fieldErrors":null}
I am not able to figure out how exactly should i parse this object.
I tried using the below code but as this not a JSONArray it throws an exception.
String getParam(String code, String element){
try {
String base = this.getItembyID(code);
JSONObject product = new JSONObject(base);
JSONArray jarray = product.getJSONArray("item");
String param = jarray.getJSONObject(0).getString("name");
return param;
} catch (JSONException e) {
e.printStackTrace();
return "error";
}
}
I recommend you use sites for json formater which show to you the types of json elements as http://json.parser.online.fr/
and
you can use Gson library for parsing json by using pojo class
public class secQueList {
public String que1;
public int ans1;
public String message;
public String nextPage;
public QuestionList secQueList;
}
public class QuestionList {
#SerializedName("1")
public String ques1;
#SerializedName("2")
public int ques2;
#SerializedName("3")
public String ques3;
#SerializedName("4")
public String ques4;
#SerializedName("5")
public String ques5;
#SerializedName("6")
public String ques6;
#SerializedName("7")
public int ques7;
#SerializedName("8")
public String ques8;
#SerializedName("9")
public String ques9;
#SerializedName("10")
public String ques10;
#SerializedName("11")
public String ques11;
}
or you can use parse using built in JSON Object
String jsonBody = the string you want to parse
JSONObject quesJsonBody = new JSONObject(jsonBody);
JSONOBject quesJson = quesJsonBody.getJSONObject("secQueList");
String quesJson1 = quesJson.getString("1");
String quesJson2 = quesJson.getString("2");
String quesJson3 = quesJson.getString("3");
String quesJson4 = quesJson.getString("4");
String quesJson5 = quesJson.getString("5");
String quesJson6 = quesJson.getString("6");
String quesJson7 = quesJson.getString("7");
String quesJson8 = quesJson.getString("8");
String quesJson9 = quesJson.getString("9");
String quesJson10 = quesJson.getString("10");
String quesJson11 = quesJson.getString("11");
String que1 = quesJsonBody.getString("que1");
String ans1 = quesJsonBody.getString("ans1");
String message = quesJsonBody.getString("message");
String fieldErrors = quesJsonBody.getString("fieldErrors");
String base = this.getItembyID(code);
JSONObject product = new JSONObject(base);
JSONOBject secQueListJson = product.getJSONObject("secQueList");
// Get all json keys "1", "2", "3" etc in secQueList, so that we can get values against each key.
Set<Map.Entry<String, JsonElement>> entrySet = secQueListJson .entrySet ();
Iterator iterator = entrySet.iterator ();
for (int j = 0; j < entrySet.size (); j++) {
String key = null; //key = "1", "2", "3" etc
try {
Map.Entry entry = (Map.Entry) iterator.next ();
key = entry.getKey ().toString ();
//key = "1", "2", "3" etc
}
catch (NoSuchElementException e) {
e.printStackTrace ();
}
if (!TextUtils.isEmpty (key)) {
Log.d ("JSON_KEY", key);
String value = secQueListJson.getString(key);
//for key = "1", value = "Which is your favorite book?"
//for key = "2", value = "Who was your childhood hero?"
}
}
Try something like this:
JSONObject jsonObject = new JSONObject(code);
JSONObject jsonObject1 = jsonObject.getJSONObject("secQueList");
for (int i=0;i<jsonObject1.length();i++){
String msg = jsonObject1.getString(String.valueOf(i));
}
You can try to use Gson to parse it. I used code below in my App in similiar case:
ArrayList<String> myArrayList;
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<String>>(){}.getType();
myArrayList= gson.fromJson(code, type);
You have to add gson to your build.grandle to have it working
compile 'com.google.code.gson:gson:2.2.+'
Extract Data from JSON String
public void ReadSMS_JSON(String JSON_String) {
String smsID = "";
String phone = "";
String message = "";
JSONObject jsonResponse = new JSONObject(JSON_String);
JSONArray jsonMainNode = jsonResponse.optJSONArray("tblsms");
if(jsonMainNode.length()>0){
JSONObject jsonChildNode = jsonMainNode.getJSONObject(0);
smsID = jsonChildNode.optString("sms_id");
phone = jsonChildNode.optString("sms_number");
message = jsonChildNode.optString("sms_message");
}
}
Currently, I'm having a minor trouble trying to get the string data from the jsonArray, however, I'm unable to get the value . I've got the data in the json object Example:
{
"lot":[
{
"id":"271",
"lot_date":"2015-05-25"
}
],
"numb3":[
{
"id":"675",
"lot_date":"2015-05-25"
}
],
"num4":[
{
"id":"676",
"lot_date":"2015-05-25"
}
],
"result":"OK"
}
The data above is stored in the JsonObject jsonobj. And what I want to do is to check if the JSON array JSONArray lot6 = jsonobj.optJSONArray("lot6"); contains the values or not , and if it's not null get the string data. However, even the data contains in the lot6 array, the result is null.
JSONArray lot6 = jsonobject.optJSONArray("lot6");
Log.d("LOT6",lot6+"");
if (lot6 != null) {
jsonarry2 = jsonobject.getJSONArray("lot6");
//3.if not null get the string data from the
for (int i = 0; i < jsonarry2.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarry2.getJSONObject(i);
ListData worldpop = new ListData();
worldpop.set_date(jsonobject.optString("lot_date"));
worldpop.set__id(jsonobject.optString("id"));
world.add(worldpop);
}
//5. test this part of the variable
String lotdate = world.get(0).get_date();
String lotid = world.get(0).get__id();
Hi please check Not lot6 its lot. please folloe below formate to get out out.
String s="{\"lot\":[{\"id\":\"271\",\"lot_date\":\"2015-05-25\"}],\"numb3\":[{\"id\":\"675\",\"lot_date\":\"2015-05-25\"}],\"num4\":[{\"id\":\"676\",\"lot_date\":\"2015-05-25\"}],\"result\":\"OK\"} ";
try{
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
String arr[]={"lot","numb3","num4"};
for(int i=0;i<json.size()-1;i++){
JSONArray ja=(JSONArray)json.get(arr[i]);
for(int j=0;j<ja.size();j++){
JSONObject jo1=(JSONObject) ja.get(j);
System.out.println("lot_date: "+jo1.get("lot_date")+" Id "+jo1.get("id"));
}
// System.out.println(ja);
}
System.out.println(json.get("result"));
}catch (Exception e) {
System.out.println(e);
}
I want to get data from a jason webservice,
JSON response is :
{"content":[{"id":"1","asset_id":"62","title":"sample page","alias":"","introtext":"","fulltext":"Some Contents"},{"id":"2","asset_id":"62","title":"sample page2","alias":"","introtext":"","fulltext":"Some Contents"},{"id":"3","asset_id":"62","title":"sample page3","alias":"","introtext":"","fulltext":"Some Contents"}]}
After Visiting Here
I have done in this way:
private void parseData() {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(BASE_URL);
try {
// Getting Array of Contents
contents = json.getJSONArray(TAG_CONTENTS);
// looping through All Contents
for(int i = 0; i < contents.length(); i++){
JSONObject c = contents.getJSONObject(i);
// Storing each json item in variable
id = c.getString(TAG_ID);
title = c.getString(TAG_TITLE);
}
textView.setText(id + " " + title);
} catch (JSONException e) {
e.printStackTrace();
}
}
Now I got id = 3 and title = sample page3result now how can I get first two values as also!!?
Arshay!! Try This One Man!!
private void parseData() {
// Creating JSON Parser instance
MyJSONParser jParser = new MyJSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(BASE_URL);
try {
// Getting Array of Contents
jsonArrar = json.getJSONArray(TAG_CONTENTS);
List list = new ArrayList<String>();
// looping through All Contents
for(int i = 0; i < jsonArrar.length(); i++){
// JSONObject c = jsonArrar.getJSONObject(i);
String id1=jsonArrar.getJSONObject(i).getString(TAG_ID);
String title=jsonArrar.getJSONObject(i).getString(TAG_TITLE);
String fullText=jsonArrar.getJSONObject(i).getString(TAG_FULL_TEXT);
list.add(id1);
list.add(title);
list.add(fullText);
}
Iterator<String> iterator = list.iterator();
StringBuilder builder = new StringBuilder();
while (iterator.hasNext()) {
String string = iterator.next();
builder.append(string+"\n");
}
textView.setText(builder);
} catch (JSONException e) {
e.printStackTrace();
}
}
Your line is JSONObject and not JSONArray.
You should use it like that:
JSONObject jso = new JSONObject(line);
JSONArray jsa = new JSONArray(jso.getJSONArray("content"));
Try something like this
// jsonData : response
List< String> contents = new ArrayList< String>();
String[] val;
try {
JSONObject jsonObj = new JSONObject(jsonData);
if (jsonObj.get(JSON_ROOT_KEY) instanceof JSONArray) {
JSONArray array = jsonObj.optJSONArray(JSON_ROOT_KEY);
for (int loop = 0; loop < array.length(); loop++) {
val = new String[loop];
JSONObject Jsonval = array.getJSONObject(loop);
val.Jsonval.getString(TAG_ID);
val.Jsonval.getString(asset_id);
.
.
etc
contents.add(val);
}
}
}