Cannot convert java string to JSON Array in Android - java

Below is the query which is fetching the data from the MySql Database but the issue is that in browser it successfully outputs the data but in Android app it gives the error which is below
Java.Long.String Cannot Convert to JsonArray
if($stem=$con->prepare("select question from MCQs where c_id=$c_id ")){
$stem->execute ();
$stem->bind_result($question);
$budget=array();
while($stem->fetch())
{
$temp=array();
$temp['question']=$question;
array_push($budget,$temp);
}
echo json_encode($budget);
Below is the Android Side Java Code for the JSON
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success.equals("1")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String questions = jsonObject1.getString("question").trim();
final String opt0ne = jsonObject1.getString("option1").trim();
;
String opttwo = jsonObject1.getString("option2").trim();
;
String optthree = jsonObject1.getString("option3").trim();
final String correctt = jsonObject1.getString("correct").trim();

JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("data");
for (int i=0;jArray.length(); i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
//try this
String msg= jsonObject1.getString("success");
}

Related

JSONObject data send to JSONArray

JSONObject data = response.getJSONObject("data");
Iterator x = data.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(data.get(key));
}
Log.d("TZX", String.valueOf(jsonArray));
I have JSONObject on variable data like this
{"type":"DISKON","result":"DUPE","data":{"1":{"Code":"DISC2","Description":"DISC SALES","Value":0},"2":{"Code":"DISC1.5%","Description":"DISC1.5%","Value":1.5},"3":{"Code":"DISC 2%","Description":"DISC 2%","Value":2}}}
How to i get Object "Value" on JSONObject for send to JSONArray on variable "jsonArray"
Sorry for my grammar and I'm newbie
谢谢
try this,
JSONObject data = response.getJSONObject("data");
JSONArray jsonArray = new JSONArray();
Iterator<?> keys = data.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (data.get(key) instanceof JSONObject) {
jsonArray.put(((JSONObject) data.get(key)).getString("Value"));
}
}
Log.e("TZX", String.valueOf(jsonArray));
You are having array, so use JsonArray directly to parse data as in
JSONArray array = response.getJSONArray("data");
List<Integer> values = new ArrayList<>();
for(int i=0;i < array.length();i++){
values.add(array.getJSONObject(i).getInt("Value"));
}
You variable data is not JSONObject it's JSONArray.
data = [{"Code":"DISC2","Description":"DISC SALES","Value":0},{"Code":"DISC1.5%","Description":"DISC1.5%","Value":1.5},{"Code":"DISC 2%","Description":"DISC 2%","Value":2}]
To get JSONObject from array
JSONArray list = new JSONArray();
JSONObject obj = new JSONObject(data)
JSONArray jsonArray = new JSONArray(obj);
for(int i=0;i<json.length();i++){
JSONObject e = jsonArray.getJSONObject(i);
String value = e.getString("Value"));
list.put(value);
}

json string to java object to populate spinner

So i have a Json string that i have retrieved from my PHP script on my MySQL server
{"Clientid":[24,26,27],"companyname":["chelsea","Microsoft","IBM"]}
and i have been trying to push this into a java objects in-order to populate a spinner at the moment the spinner on each line shows "chelsea","Microsoft","IBM" but i would like to show each company on a separate line so the user can select which company
current code
String response = stringBuilder.toString();
Log.d("response", response);
JSONObject jsonResponse = new JSONObject(response);
Log.d("response", jsonResponse.toString());
responseStreamReader.close();
Log.d("length", Integer.toString(jsonResponse.length()));
if (jsonResponse.length() == 0) {
returnedClient = null;
} else {
List<Client> myClients;
myClients = new ArrayList<Client>();
for (int i = 0; i < jsonResponse.length(); i++) {
Client client = new Client();
client.clientid = jsonResponse.getString("Clientid");
client.companyname = jsonResponse.getString("companyname");
myClients.add(client);
}
returnedClient = myClients;
}
} catch (Exception e) {
e.printStackTrace();
}
//Log.d("returnedUser", returnedUser.userpassword);
return returnedClient;
current code is obviously the wrong code so i have been looking at Gson and Jackson and volley and getting in a mess so i have been looking at the below but cant get it right to fit the Json string so wondered if you could help please or advise a better solution?
JSONArray jarray = jsonResponse.getJSONArray("companyname");
ArrayList<String> xyz= new ArrayList<String>();
for(int i = 0; i < jarray.length(); i++){
JSONArray timeArray =jarray.getJSONObject(i).getJSONArray("companyname");
for(int j = 0; j < timeArray .length(); j++){
xyz.add(timeArray .getString(j));
Log.d("get value",timeArray .getString(j));
Is there something im missing with the parser as doesnt matter what i change it seems to not like anything i do, it says the json cant be an object then it cant be an array, i assume the json is an object then an array but at the mormnt i just get errors :(
try {
List<Client> returnedClient = null;
// JSONObject json = new JSONObject(content);
JSONArray json1 = new JSONArray(content);
//JSONObject dataObject1 = json.getJSONObject("Clientid");
//JSONObject dataObject2 = json.getJSONObject("companyname");
// JSONArray items1 = json.getJSONArray("Clientid");
// JSONObject items2 = json.getJSONObject("companyname");
// JSONArray items1 = json.getJSONArray("Clientid");
JSONArray items2 = json1.getJSONArray(0);
for (int i = 0; i < items2.length(); i++) {
// JSONArray clientObject1 = items1.getJSONArray(i);
// JSONObject clientObject2 = items2.getJSONObject(i);
JSONArray clientObject3 = items2.getJSONArray(i);
// Client client = new Client(clientObject2);
Log.d("response",clientObject3.toString());
// returnedClient.add(client);
}
O silly me the is was further up the tree as i was using the code below at the top of the page before i even started the parse, shame it took me to re write my sql before i noticed :(
JSONObject jsonResponse = new JSONObject(response);

Get JSON Array into strings.

I have a webservice which returns a JSON array in this format:
[{"imageid":"3","userid":"1","imagepath":"SLDFJNDSKJFN","filterid":"1","dateadded":"2014-05-06 21:20:18.920257","public":"t"},
{"imageid":"4","userid":"1","imagepath":"dsfkjsdkfjnkjdfsn","filterid":"1","dateadded":"2014-05-06 21:43:37.642748","public":"t"}]
I need to get all the attributes seperately? How would I do this?
I know how to do it with JSONObject if there is just 1 thing being returned, but how does it work when multiple items are returned?
Thanks
try {
JSONArray jArray = new JSONArray(jsonString);
String s = new String();
for (int i = 0; i < jArray.length(); i++) {
s = jArray.getJSONObject(i).getString("imageid").toString();
s = jArray.getJSONObject(i).getString("userid").toString();
}
} catch (JSONException je) {
}
Create an Object class with all variables, create a List for this Object, add all objects in your JSONArray to the list, use the one you need.
List<YourObject> objList = new ArrayList<YourObject>();
JSONArray a = new JSONArray(response);
int size = a.length();
for (int i=0 ; i<size ; i++){
JSONObject aa = a.getJSONObject(i);
String id = aa.getString("imageid");
String userid = aa.getString("userid");
String imagepath = aa.getString("imagepath");
String filterid = aa.getString("filterid");
String dateadded = aa.getString("dateadded");
String publicText = aa.getString("public");
YourObject obj = new YourObject(id,userid,imagepath,filterid,dateadded,publicText);
objList.add(obj);
}
So what you are having here is some JSON objects inside a JSON array.
What you want to do is this:
JSONArray array = ...;
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
// Extract whatever you want from the JSON object.
}
I hope it helped.
You can use JSONArray to parse array of JSON response.
private void parseJsonArray(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String ImageId = jsonObject.getString("imageid");
Log.v("JSON Parser", "ImageId: "+ImageId);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Parsing JSON Array with JSON OBJECT

I have some JSON with the following structure:
{"cit": [
"ALL",
"Aceh Barat",
"Aceh Besar",
"Aceh Jaya",
"Aceh Selatan",
"Aceh Tengah",
"Aceh Timur",
"Aceh Utara"]}
i have try to parsing my json like this :
JSONObject jsonObject = new JSONObject(result);
JSONArray city=jsonObject.getJSONArray("cit");
for (int j=0; j < city.length(); j++){
JSONObject cit = city.getJSONObject(j);
String kot = cit.toString(j);
kota.add(kot);
}
on post execute :
ArrayAdapter<String> SpinnerKota = new ArrayAdapter<String>(Pencarian.this, android.R.layout.simple_list_item_1, kota);
spin_kota.setAdapter(SpinnerKota);
but nothing happen, is there any wrong with my code? i hope someone can help me to solve my problem.
"cit": [ // json array cit
"ALL", // index 0 is ALL
Also there is no json object inside json array cit. So you don't need this JSONObject cit = city.getJSONObject(j).
Change
String kot = cit.toString(j);
To
String kot = (String) city.get(j);
Use the below
JSONObject jsonObject = new JSONObject("myjson string");
JSONArray city=jsonObject.getJSONArray("cit");
for(int i=0;i<city.length();i++)
{
String cities = (String) city.get(i);
Log.i("All Cities",cities);
kota.add(cities);
}
Do it like this
JSONArray json = jParser.getJSONFromUrl(URL);
JSONObject c = json.getJSONObject(0);
JSONArray city = c.getJSONArray("cit");
for (int j=0; j < city.length(); j++){
String kot = cit.get(j);
kota.add(kot);
}
Object obj = yourJsonResult;
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("cit");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
you can do it as following code this is tested
String jsonSource="{'cit': ['ALL','Aceh Barat','Aceh Besar','Aceh Jaya','Aceh Selatan','Aceh Tengah','Aceh Timur','Aceh Utara']}";
try {
JSONObject jsonObject=new JSONObject(jsonSource);
JSONArray jsonArray=jsonObject.getJSONArray("cit");
int length = jsonArray.length();
String [] cities = new String [length];
if (length > 0) {
for (int i = 0; i < length; i++) {
cities[i] = jsonArray.getString(i);
}
}
//to check we can print our string array
for (int i = 0; i < cities.length; i++) {
Log.d("JSON parsing ",cities[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}

Processing a JSON string into a Java Array

I have this array in json code.
$info=array();
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
array_push($info,$row);
}
$info;
$result_final->lugares_cercanos = $info;
Print this:
{"logstatus":"1","lugares_cercanos":[{"nombre":"Rio Amazonas","distancia":"5119.000"}{"nombre":"Swissotel Quito","distancia":"5823.000"}{"nombre":"Laguna de Yaguarcocha","distancia":"71797.000"}]}
Now, the problem is, How can I put the fields of "lugares_cercanos" into java ArrayList??
I try with this code:
{
JSONArray jdata=post.getserverdata(postparameters2send, URL_connect);
if (jdata!=null && jdata.length() > 0){
JSONObject json_data;
ArrayList<NameValuePair> lugares = new ArrayList<NameValuePair>();
json_data = jdata.getJSONObject(0);
logstatus=json_data.getInt("logstatus");
lugaresCercanos=json_data.getJSONArray("lugares_cercanos");
for (int i = 0; i < lugaresCercanos.length(); ++i) {
JSONObject rec = lugaresCercanos.getJSONObject(i);
String name = rec.getString("nombre");
String dist = rec.getString("distancia");
lugares.add(new BasicNameValuePair(name,dist));
}
}
}
Try this:
JSONObject j = jdata.getJSONObject("obj");
JSONArray jArray = j.getJSONArray("lugares_cercanos");
int len = jArray .length();
for(int i=0; i <len; i++){
String nombre = jArray .getJSONObject(i).optString("nombre");
---------
}
The top level structure (i.e. the JSON string you have posted) is not an array but an object.
I don't know what your post.getserverdata method does, if there is a version that can return a JSONObject you could use:
JSONObject jdata=post.getserverdataobject(postparameters2send, URL_connect);
logstatus=jdata.getInt("logstatus");
lugaresCercanos=jdata.getJSONArray("lugares_cercanos");
...
show this error:
Error parsing data org.json.JSONException: Value {"lugares_cercanos":[{"nombre":"Laguna de Yaguarcocha","distancia":"8686205.000"},{"nombre":"Swissotel Quito","distancia":"8728811.000"},{"nombre":"Rio Amazonas","distancia":"8729333.000"}],"logstatus":"1"} of type org.json.JSONObject cannot be converted to JSONArray

Categories

Resources