I have a problem with Json in android. In 4+ it works like a charm but in 2.2 it fails. I'm really stuck here.
I get error I get error: java.lang.ClassCastException: java.lang.String
In my server I parse array as:
[{"PRODUCT":
{"product_id":"1",
"name":"name1"}},
{"PRODUCT":
{"product_id":"2",
"name":"name2"}},
{"PRODUCT":
{"product_id":"3",
"name":"name3"}},
{"USER":{"user_id":"1"}
}]
in android app i use code as:
public void buildData(String jsonString, String code) {
mProduct = new HashMap<Integer, Product>();
try {
**here fails -> JSONArray array = (JSONArray) new JSONTokener(jsonString).nextValue();
// Object object = new JSONTokener(jsonString).nextValue();
// object = (object instanceof JSONArray) ? (JSONArray)object : (JSONObject)object ;
// JSONObject obj = (JSONObject) new JSONTokener(jsonString).nextValue();
for(int i = 0; i < array.length(); i++){
JSONObject json = array.getJSONObject(i);
if(json.has(JSON_PRODUCT)){
buildProduct(json.getString(JSON_PRODUCT), code);
}
else if(json.has(JSON_NAME)){
buildUser(json.getString(JSON_NAME));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I'm not sure if the array is in the right form? If anyone can help me please.
I believe you should change the line to the following:
JSONArray array = new JSONArray(jsonString);
Then you can loop through it.
Related
I'm trying to get the value of elevations from JSON in android but in the log nothing is shown. This JSON is a nested array, I'm still new toth parsing JSON in android.
This is what the JSON looks like :
This is my code :
try {
JSONObject responseObject = new JSONObject(result);
JSONArray elev = responseObject.getJSONArray("resourceSets");
JSONArray el = elev.getJSONObject(1).getJSONArray("elevations");
for(int i=0; i<=el.length();i++){
Log.d("EL",el.toString());
}
}
catch (Exception e){
e.printStackTrace();
}
try like below: (problem in your code is you are getting "elevations" directly without getting "resources" array)
try {
JSONObject responseObject = new JSONObject(result);
JSONArray elev = responseObject.getJSONArray("resourceSets");
JSONArray el_resources = elev.getJSONObject(0).getJSONArray("resources");
JSONArray el = el_resources.getJSONObject(0).getJSONArray("elevations");
for(int i=0; i<=el.length();i++){
Log.d("EL", el[i].toString()); // also get index from array then print it
}
}
catch (Exception e){
e.printStackTrace();
}
I get a problem when I parse this text as JSON. First, I created jsonobject from an URL. I can't show data when debugging, can anyone help me?
JSON:
[
{
"Tarih":"21.12.2015",
"Imsak":"05:51",
"Gunes":"07:22",
"Ogle":"12:18",
"Ikindi":"14:39",
"Aksam":"17:02",
"Yatsi":"18:26",
"Kible":"09:41"
}
]
I tried this code to solve it, but the JSON wasn't correctly parsed:
Java Code:
jsonobject = JSONfunctions.getJSONfromURL("http://namazvakitleri.ahmeti.net/index.php?islem=getSehirList&ulke_id=2");
try {
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("d");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
WorldPopulation worldpop = new WorldPopulation();
worldpop.setCountry(jsonobject.optString("SehirId"));
worldpop.setPopulation(jsonobject.optString("population"));
world.add(worldpop);
// Populate spinner with country names
worldlist.add(jsonobject.optString("SehirAdi"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
'[' indicates a JsonArray whereas '{' indicates a JsonObject. You have assigned the result to the JsonObject. Instead of that assign it to JsonArray.
Also I don't see any key as "d" in you response.
Try this :
jsonarray = JSONfunctions
.getJSONfromURL("http://namazvakitleri.ahmeti.net/index.php?islem=getSehirList&ulke_id=2");
try {
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
WorldPopulation worldpop = new WorldPopulation();
worldpop.setCountry(jsonobject.optString("SehirId"));
worldpop.setPopulation(jsonobject.optString("population"));
world.add(worldpop);
// Populate spinner with country names
worldlist.add(jsonobject.optString("SehirAdi"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
But again please note your response does not contain this keys 'SehirId', 'population' and 'SehirAdi'
Your response is JsonArray not a JsonObject.
Now you have two ways to solve this problem.
change your getJSONfromURL() to return JsonArray
change response from server to return JsonObject instead of JsonArray
after doing above changes you must need to parse it according to your response.
Note : You have catch block available, so please try to check error in logcat and search on google related to that error.
try this solution :
try {
JSONArray jsonArray = new JSONArray("Your Response");
JSONObject jsonObject = (JSONObject) jsonArray.get(0);
Iterator keyNames = jsonObject.keys();
while (keyNames.hasNext()) {
String keyName = (String) keyNames.next();
String keyValue = jsonObject.getString(keyName);
}
} catch (Exception e) {
e.printStackTrace();
}
I am receiving a String response from the following #Override method
#Override
publc void onSuccess(String response) {
....
}
The conflict I am facing is that I do not know how to break up this response into key value pairings. This is an example of the response.
{"action":{"generic_message":"test generic message"},"domains":{"key_example_one":"https:/google.com","api_root_url":"https://test.com/new/0.2/json"},"page":null}}
I have attempted to convert the string to a JSONObject, and then adding the JSONObjects to a JSONArray.
JSONObject mJObj;
try {
mJObj = new JSONObject(response);
JSONArray mJArry = mJObj.getJSONArray("action");
for (int i = 0; i < mJArry.length(); i++) {
JSONObject newObj = mJArry.getJSONObject(i);
String test2 = newObj.getString("generic_example_for_all_platforms");
}
} catch (JSONException e) {
e.printStackTrace();
}
EDIT: I am getting JSON exception that JSONArray cannot be converted to JSONObject, for the following line.
JSONArray mJArry = mJObj.getJSONArray("action");
Thanks in advante
You do want to read more about JSON here.
The first thing to know is that {} is equal to a Json Object and [] is equal to a Json Array.
try {
JSONObject mJObj = new JSONObject(response);
JSONObject actionJsonObject = mJObj.getJSONObject("action");
String generic_message = actionJsonObject.getString("generic_message");
JSONObject domainsJsonObject = mJObj.getJSONObject("domains");
String key_example_one = domainsJsonObject.getString("key_example_one");
String api_root_url = domainsJsonObject.getString("api_root_url");
String page = mJObj.getString("page");
} catch (JSONException e) {
e.printStackTrace();
}
Check out Gson.
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
EDIT:
Just saw that you can't move to other Json processors. The property 'action' holds a JSONObject not a JSONArray. What about JSONObject jsonObject = mJObj.getJSONObject("action").
I've got a slight problem with a getString function in my Android code.
I create a string and I want to use it to retrieve a String which is part of a JSON Array but I get the following error:
The method getString(String) is undefined for the type String
This is the specific code for this section:
private void read_JSON()
{
JSONArray jsa2 = new JSONArray();
for (int i=0; i < jsa2.length(); i++)
{
try
{
JSONObject jso2 = new JSONObject();
jso2 = jsa2.getJSONObject(i);
String one = one.getString("Blur");
//esbrinar com arreglar aixo!!
}catch (JSONException e)
{
e.printStackTrace();
}
}
}
"Blur" is a String which is part of a JSONArray, defined here:
private void create_JSON()
{
JSONObject jso = new JSONObject();
try {
jso.put("Nombre","Miguel");
jso.put("Apellidos", "Garcia");
jso.put("Año_nacimiento", 1990);
JSONArray jsa = new JSONArray();
jsa.put("Blur");
jsa.put("Clur");
jso.put("Nombres_Hijos", jsa);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Could you help me understand what I'm doing wrong?
Thank you very much.
Yours sincerely,
Mauro.
jso2.getString("Blur") might be what you're trying to call. I believe you want to extract a string from the JSONObject you just got from JSONArray. What you actually wrote is to extract string from the string you just defined.
I've got a json object, which is being collected into a function as string.
It contains array
{"officer_name":"V. M. ARORA"}{"officer_name":"Dr. C. P.
REDDY"}{"officer_name":"ARTI CHOWDHARY"}{"officer_name":"JAGDISH
SINGH"}
and here is the android code
public void func4(View view)throws Exception
{
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("pLat", "SELECT officer_name FROM iwmp_officer");
client.post("http://10.0.2.2/conc5.php", rp, new AsyncHttpResponseHandler() {
public final void onSuccess(String response) {
// handle your response here
ArrayList<String> User_List = new ArrayList<String>();
try {
/* here I need output in an array,
and only names not the "officer_name" */
} catch (Exception e) {
tx.setText((CharSequence) e);
}
//tx.setText(User_List.get(1));
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
tx.setText(response);
}
});
}
The output I've shown above is in String, need to get it in array. Please help!
If the output you got is something like this.
String outputJson=[{"officer_name":"V. M. ARORA"}{"officer_name":"Dr. C. P. REDDY"}{"officer_name":"ARTI CHOWDHARY"}{"officer_name":"JAGDISH SINGH"}]
Then its a JSON Array.
You can parse it as
JsonArray array=new JsonArray(outputJson);
Then loop this json array using
for(JsonObject jsonObj in array){
String officerName=[jsonObj getString("officer_name");
}
You can use something like above The mentioned code is not correct syntactically but yes conceptually correct. You can go ahead with this.
List < String > ls = new ArrayList< String >();
JSONArray array = new JSONArray( response );
for (int i = 0; i < array.length() ; i++ ) {
JSONObject obj = array.getJSONObject(Integer.toString(i));
ls.add(obj.getString("officer_name"));
}
This would work
try {
JSONArray array= new JSONArray(response);
//array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
//JSONObject obj = response.getJSONArray(i);
JSONObject jsonLineItem = (JSONObject) array.getJSONObject(i);
String name_fd = jsonLineItem.getString("officer_name");
User_List.add(jsonLineItem.getString("officer_name"));
Log.d("JSONArray", name_fd+" " +name_fd);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tx.setText( e.toString());
}