Here is the way i was going to do it but I get an error in the line JSONObject c = orders.getJSONObject(i);:
Error:(95, 57) error: incompatible types: int cannot be converted to String
Maybe there is a better way of doing this process , please help
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> param = new ArrayList<NameValuePair>();
JSONObject json = jsonParser.makeHttpRequest(URL_ORDERS, "GET",
param, token);
JSONObject data = json.getJSONObject("data");
JSONObject orders = data.getJSONObject("orders");
Log.d("JSON DATA", data.toString());
Log.d("JSON ORDERS", orders.toString());
for (int i = 0; i < orders.length(); i++) {
JSONObject c = orders.getJSONObject(i);
imageurl = c.getString(TAG_IMAGE);
Log.d("IDK", imageurl);
title = c.getString(TAG_TITLE).substring(0, 20);
price = c.getString(TAG_PRICE);
status = c.getString(TAG_PSTATUS);
symbol = c.getString(TAG_PRICESYMBOL);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_PRICE, price);
map.put(TAG_PSTATUS, status);
map.put(TAG_PRICESYMBOL, symbol);
map.put(TAG_IMAGE, imageurl);
orderList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Your orders object is a JSONObject (with the order IDs being used as keys and the complete order objects as values), but in your code you're treating it as a JSONArray.
You probably want to change your loop as follows:
Iterator<String> orderIterator = orders.keys();
while (orderIterator.hasNext()) {
JSONObject c = orders.getJSONObject(orderIterator.next());
// ...
}
The call to keys() will return an iterator over the object's keys (in this case order IDs). Then it's just a matter of using the iterator to loop over all the keys, and retrieve each order object using getJSONObject.
Related
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()
}
I want to first get particuler data from JsonObject then i also want to set that JsonObject as parallel data. I think it is possible with HashMap. But i do not know how to set data as parallel JsonObject. And How to use ?
Please Help me.
I want to each name with each own JsonObject.
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
String name = json.optString("username");
list.add(json);
}
You can do like this
You declare global variable
private HashMap<String, JSONObject> mHashMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.admin_frag_update_driver, container, false);
mHashMap = new HashMap<String, JSONObject>();
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
String name = json.optString("username");
list.add(json);
mHashMap.put(name , object);
}
JSONObject object = mHashMap.get(name );
}
Try this way it will help
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(INTEREST_ACCEPT_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
interestaccept = jsonObj.getJSONArray(INTEREST_ACCEPT);
for (int i = 0; i < interestaccept.length(); i++) {
JSONObject c = interestaccept.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(INTERESTACCEPT_USER_ID, c.getString(INTERESTACCEPT_USER_ID));
map.put(INTEREST_ACCEPT_NAME,c.getString(INTEREST_ACCEPT_NAME));
map.put(INTEREST_ACCEPT_PROFILE, c.getString(INTEREST_ACCEPT_PROFILE));
map.put(INTEREST_ACCEPT_IMAGE, c.getString(INTEREST_ACCEPT_IMAGE));
map.put(INTEREST_ACCEPT_CAST, c.getString(INTEREST_ACCEPT_CAST));
map.put(INTEREST_ACCEPT_AGE, c.getString(INTEREST_ACCEPT_AGE)+" years");
map.put(INTEREST_ACCEPT_LOCATION, c.getString(INTEREST_ACCEPT_LOCATION));
// adding HashList to ArrayList
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
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 have a problem with json.
I get this response from server:
{"TESTS":true,"TESTS_VIEW":true,"ORDER":true,"PARAMETERS":true,"VIEW":true}
How can I save this data in array or something else to have schema: key - value?
Hmm, not sure I understand why you want this. A JSONObject gives you exactly that, have a look at JSONObject.get():
JSONObject json = new JSONObject(yourjsonstringfromserver);
boolean tests = json.getBoolean("TESTS");
Still, if you want to iterate over all values you can do like this:
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keys = json.keys();
for(String key : keys) {
try {
Object value = json.get(key);
map.put(key, value);
}
catch (JSONException e) {
// Something went wrong!
}
}
JSONObject object = YourObjectHere;
Map<String,Boolean> dict = new HashMap<String,Boolean>();
Iterator it = object.keyes();
while( it.hasNext() ){
String key = it.next();
String value = object.get(key);
dict.put( key, value );
}
Solution, more or less. //Written without checking in IDE so may contain bugs/errors
JSONObject json = new JSONObject(response);
json.getInt(keyA);
json.getString(keyB);
and etc;
You can using this function with httpResponse is your json string:
public static YourModel parseJson(String httpResponse) {
YourModel objObject = new YourModel();
try {
JSONArray jsonArrayData = new JSONArray(httpResponse);
if (jsonArrayData.length() >= 1) {
for (int i = 0; i < jsonArrayData.length(); i++) {
JSONObject object = new JSONObject(jsonArrayData.get(0));
// Setting value by key json
objObject.setAtrr(object.getString("YourKey"));
}
}
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return objObject;
}
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);
}
}
}