I'd like to parse the following items from JSON data below: title, year, runtime, critics consensus, the theater release date, the synopsis, poster thumbnails, and poster originals. But when I parse my data I get a JSON Exception: No value for TAG_TITLE, and basically nothing happens.
{"query": {
"count": 30,
"created": "2014-01-16T14:39:33Z",
"lang": "en-US",
"results": {
"movies": [
{
"id": "13065",
"title": "Gladiator",
"year": "2000.0",
"mpaa_rating": "R",
"runtime": "171.0",
"critics_consensus": "Ridley Scott and an excellent cast successfully convey the intensity of Roman gladitorial combat as well as the political intrigue brewing beneath.",
"release_dates": {
"theater": "2000-05-05",
"dvd": "2000-11-21"
},
"ratings": {
"critics_rating": "Certified Fresh",
"critics_score": "76.0",
"audience_rating": "Upright",
"audience_score": "87.0"
},
"synopsis": "",
"posters": {
"thumbnail": "http://content6.flixster.com/movie/11/16/89/11168944_mob.jpg",
"profile": "http://content6.flixster.com/movie/11/16/89/11168944_pro.jpg",
"detailed": "http://content6.flixster.com/movie/11/16/89/11168944_det.jpg",
"original": "http://content6.flixster.com/movie/11/16/89/11168944_ori.jpg"
},
"abridged_cast": [
{
"name": "Russell Crowe",
"id": "162652569",
"characters": "Maximus"
},
{
"name": "Joaquin Phoenix",
"id": "162655394",
"characters": "Commodus"
},
{
"name": "Connie Nielsen",
"id": "162653203",
"characters": "Lucilla"
},
{
"name": "Oliver Reed",
"id": "162662908",
"characters": "Proximo"
},
{
"name": "Derek Jacobi",
"id": "162656362",
"characters": "Gracchus"
}
],
"alternate_ids": {
"imdb": "0172495"
},
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065.json",
"alternate": "http://www.rottentomatoes.com/m/gladiator/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065/cast.json",
"clips": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065/clips.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065/reviews.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065/similar.json"
}
}
This is the code for extracting the data I want:
jsonObject = new JSONObject(result);
JSONObject queryJSONObject = jsonObject.getJSONObject("query");
JSONObject resultsJSONObject = queryJSONObject.getJSONObject("results");
JSONArray moviesJSONArray = resultsJSONObject.getJSONArray("movies");
for(int i = 0; i < moviesJSONArray.length(); i++){
JSONObject c = moviesJSONArray.getJSONObject(i);
String title = c.getString("TAG_TITLE");
String year = c.getString("TAG_YEAR");
String mpaa_rating = c.getString("TAG_RATING");
String runtime = c.getString("TAG_RUNTIME");
String critics_consensus = c.getString("TAG_CONSENSUS");
JSONObject dates = c.getJSONObject("release_dates");
String theater = dates.getString("TAG_THEATER");
JSONObject posters = c.getJSONObject("posters");
String thumbnail_posters = posters.getString("TAG_TBPOSTER");
String original_posters = posters.getString("TAG_ORIPOSTER");
Log.e(TAG,
", Title: " + title
+ ", Year: " + year
+ ", Rating: " + mpaa_rating
+ ", Runtime: " + runtime
+ ", Consensus :" + critics_consensus
+ ", Theater date: " + theater
+ ". Poster small: " + thumbnail_posters
+ ", Poster big: " + original_posters
);
HashMap<String, String> movie = new HashMap<String, String>();
movie.put(TAG_TITLE, title);
movie.put(TAG_YEAR, year);
movie.put(TAG_RATING, mpaa_rating);
movie.put(TAG_RUNTIME, runtime);
movie.put(TAG_CONSENSUS, critics_consensus);
movie.put(TAG_THEATER, theater);
movie.put(TAG_TBPOSTER, thumbnail_posters);
movie.put(TAG_ORIPOSTER, original_posters);
moviesList.add(movie);
And before my OnCreate I'm using these Strings for the TAGS:
private static final String TAG_CONSENSUS = "critics_consensus";
private static final String TAG_RATING = "mpaa_rating";
private static final String TAG_YEAR = "year";
private static final String TAG_THEATER = "theater";
private static final String TAG_TITLE = "title";
private static final String TAG_RUNTIME = "runtime";
private static final String TAG_DATE = "theater";
private static final String TAG_TBPOSTER = "thumbnail_posters";
private static final String TAG_ORIPOSTER = "original_posters";
JSONArray movies = null;
ArrayList<HashMap<String, String>> moviesList;
My TAG_TITLE is "title" which is also used in the JSON Data so I'm at a loss as to why I get this error? Or is my code wrong? Thanks in advance
Shouldn't you do
String title = c.getString(TAG_TITLE);
instead of
String title = c.getString("TAG_TITLE");
?
You should have to either write String directly like
JSONObject jsonobject = new JSONObject(jsonString);
JSONObject queryjson = jsonobject.getJSONObject("query");
String count = queryjson.getString("count");
OR
//This Code is As per Your Coding
JSONObject jsonobject = new JSONObject(jsonString);
JSONObject queryjson = jsonobject.getJSONObject(TAG_QUERY);
String count = queryjson.getString(TAG_COUNT);
Inshort Just Remove The " " before Or After String Name TAG_..
Related
Hi guys i got a problem with Expected a string but was BEGIN_OBJECT
i i cant find a solution been browsing for 2 days now , need help to fix this thanks
im storing the json content on a DB but on my json i got a nested array ,
this is my 1 item on my json file
[
{
"id": "355",
"indicaciones": "text",
"efectos_secundarios": "text",
"contraindicaciones": "",
"precauciones_advertencias": "text",
"interacciones": "",
"nombre_principio_activo": "Decoquinato",
"especies": [
{
"especies_id": "1"
},
{
"especies_id": "2"
},
{
"especies_id": "3"
},
{
"especies_id": "4"
},
{
"especies_id": "9"
}
]
}
]
this is my model with contructor and getters and seters
private int id;
private String indicaciones;
private String dosis_via_administracion;
private String efectos_secundarios;
private String contraindicaciones;
private String precauciones_advertencias;
private String nombre_principio_activo;
private String especies;
my api
#GET("formulario.txt")
Call<List<FormularioModel>> getFormularios();
this is my retrofit, where im lossing my mind
//store formilarion on database
public void storeFormulariosToDb(){
Retrofit retrofitCat = new Retrofit.Builder()
.baseUrl(ApiForm.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiForm apicat = retrofitCat.create(ApiForm.class);
Call<List<FormularioModel>> callCat = apicat.getFormularios();
callCat.enqueue(new Callback<List<FormularioModel>>() {
#Override
public void onResponse(Call<List<FormularioModel>> callCat, Response<List<FormularioModel>> response) {
List<FormularioModel> obtenercate =db.getALLFormulario();
List<FormularioModel> cat = response.body();
if(obtenercate.size() < cat.size()){
for(int i = 0; i < cat.size(); i++){
FormularioModel cat1 = new FormularioModel(
cat.get(i).getId(),
cat.get(i).getIndicaciones(),
cat.get(i).getDosis_via_administracion(),
cat.get(i).getEfectos_secundarios(),
cat.get(i).getContraindicaciones(),
cat.get(i).getPrecauciones_advertencias(),
cat.get(i).getNombre_principio_activo(),
cat.get(i).getEspecies()); // Here is my problem
db.createFormularios(cat1);
}
}
}
#Override
public void onFailure(Call<List<FormularioModel>> callCat, Throwable t) {
Log.e("obtener formulario", t.getMessage()); }
});
}
and this one is my DBHelper to store to db
public long createFormularios(FormularioModel itemFORM){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues valores = new ContentValues();
valores.put(FORMULARIO_ID, itemFORM.getId());
valores.put(FORMULARIO_INDICA, itemFORM.getIndicaciones());
valores.put(FORMULARIO_VIA, itemFORM.getDosis_via_administracion());
valores.put(FORMULARIO_EFECT, itemFORM.getEfectos_secundarios());
valores.put(FORMULARIO_CONTRA, itemFORM.getContraindicaciones());
valores.put(FORMULARIO_PRECA, itemFORM.getPrecauciones_advertencias());
valores.put(FORMULARIO_NOMBRE, itemFORM.getNombre_principio_activo());
valores.put(FORMULARIO_ESPECIE, itemFORM.getEspecies());
long formulario_id = db.insert(TABLE_FORMULARIOS, null, valores);
return formulario_id;
}
and for read my db
public List<FormularioModel> getALLFormulario(){
List<FormularioModel> forms = new ArrayList<>();
String selectQuery = " SELECT * FROM "
+ TABLE_FORMULARIOS
+ " ORDER BY "
+ FORMULARIO_NOMBRE + " ASC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery,null);
if(c.moveToFirst()){
do{
FormularioModel t = new FormularioModel();
t.setId(c.getInt(c.getColumnIndex(FORMULARIO_ID)));
t.setIndicaciones(c.getString(c.getColumnIndex(FORMULARIO_INDICA)));
t.setDosis_via_administracion(c.getString(c.getColumnIndex(FORMULARIO_VIA)));
t.setEfectos_secundarios(c.getString(c.getColumnIndex(FORMULARIO_EFECT)));
t.setContraindicaciones(c.getString(c.getColumnIndex(FORMULARIO_CONTRA)));
t.setPrecauciones_advertencias(c.getString(c.getColumnIndex(FORMULARIO_PRECA)));
t.setNombre_principio_activo(c.getString(c.getColumnIndex(FORMULARIO_NOMBRE)));
t.setEspecies(c.getString(c.getColumnIndex(FORMULARIO_ESPECIE)));
forms.add(t);
} while (c.moveToNext());
}
return forms;
}
i wants to save the especies array as String to be able to display it on my activity ,
thanks for the help
problem is with your model class especies is not string its list of objects
in your model change private String especies; to private List<Especies> especies; and create a class named Especies like below
public class Especies {
private String especies_id;
...
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Need Help
I have Json through which i have to retrieve objects but unable to retrieve.
I have used multiple objects also to retrieve but no success.
JSON:
{
"status": 1,
"data": [{
"restaurent_id": "1",
"user_id": "6",
"zone_id": "1",
"restaurentAddress": {
"restaurent_address_id": "1"
},
"restaurentInfo": {
"restaurent_info_id": "1",
"restaurent_bussiness_owner_name": "Vijay"
},
"restaurentSetting": {
"restaurent_setting_id": "1",
"minimum_purcase": "200",
"payment_method_id": "1",
"title": "Best Hotel"
},
"zone": {
"zone_id": "1",
"by_zipcode": "1"
}
}]
}
and i want to fetch restaurentAddress and restaurentInfo
MY mainActivity.java file
package com.example.premi.jsonlist;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView output = (TextView) findViewById(R.id.textView1);
String strJson="{\n" +
"\t\"status\": 1,\n" +
"\t\"data\": [{\n" +
"\t\t\"restaurent_id\": \"1\",\n" +
"\t\t\"user_id\": \"6\",\n" +
"\t\t\"zone_id\": \"1\",\n" +
"\t\t\"restaurentAddress\": {\n" +
"\t\t\t\"restaurent_address_id\": \"1\"\n" +
"\t\t},\n" +
"\t\t\"restaurentInfo\": {\n" +
"\t\t\t\"restaurent_info_id\": \"1\",\n" +
"\t\t\t\"restaurent_bussiness_owner_name\": \"Vijay\"\n" +
"\t\t},\n" +
"\t\t\"restaurentSetting\": {\n" +
"\t\t\t\"restaurent_setting_id\": \"1\",\n" +
"\t\t\t\"minimum_purcase\": \"200\",\n" +
"\t\t\t\"payment_method_id\": \"1\",\n" +
"\t\t\t\"title\": \"Best Hotel\"\n" +
"\t\t},\n" +
"\t\t\"zone\": {\n" +
"\t\t\t\"zone_id\": \"1\",\n" +
"\t\t\t\"by_zipcode\": \"1\"\n" +
"\t\t}\n" +
"\n" +
"\t}]\n" +
"}";
String dataoutput = "";
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONObject status = jsonRootObject.optJSONObject("status");
JSONArray Dataarray =status.getJSONArray("data");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < Dataarray.length(); i++){
JSONObject jsonObject = Dataarray.getJSONObject(i);
JSONObject Data = jsonObject.getJSONObject("restaurentAddress");
for(int j = 0 ; j < Data.length(); j++){
JSONObject GetData =Data.getJSONObject(String.valueOf(j));
int id = Integer.parseInt(GetData.getString("restaurent_address_id"));
String postcode = GetData.getString("postcode");
String addresss = GetData.getString("restaurent_address");
dataoutput += " : \n id= "+ id +" \n postcode= "+ postcode +" \n address= "+ addresss +" \n ";
}}
output.setText(dataoutput);
} catch (JSONException e) {e.printStackTrace();}
}
}
Try this out:
try {
JSONObject object = (JSONObject) new JSONTokener(YOUR_JSON_STRING).nextValue();
String restaurentAddressId = object.getJSONArray("data").getJSONObject(0).getJSONObject("restaurentAddress").getString("restaurent_address_id");
String restaurentInfoId = object.getJSONArray("data").getJSONObject(1).getJSONObject("restaurentInfo").getString("restaurent_info_id");
String restaurentBizOwnerName = object.getJSONArray("data").getJSONObject(1).getJSONObject("restaurentInfo").getString("restaurent_business_owner_name");
}
catch (JSONException e) {
}
Its Done I tried this
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray mainnode =jsonRootObject.getJSONArray("data");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < mainnode.length(); i++){
JSONObject jsonObject = mainnode.getJSONObject(i);
JSONObject Data = jsonObject.getJSONObject("restaurentInfo");
int id = Integer.parseInt(Data.getString("restaurent_info_id"));
String postcode = Data.getString("restaurent_phone_number");
String addresss = Data.getString("restaurent_bussiness_owner_name");
dataoutput += " : \n restaurent_id= "+ id +" \n restaurent_info_id= "+ postcode +" \n restaurent_address_id= "+ addresss +" \n ";
}
output.setText(dataoutput);
} catch (JSONException e) {e.printStackTrace();}
}
I just removed Status Object
and another for loop Thanks For the Help Got little Bit Help from You :)
How to store nested JSONArray value in SQLite Database?
getting value from JSONArray and It is also stored it in ArrayList both working fine.
My JSONArray List is,
{
"resultFlag": true,
"successMessage": "Data Received",
"Questions": [
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "64",
"question": "Which section of the Indian IT act 2008 deals with cyber stalking?",
"answer": [
{
"ansID": "261",
"ans": "Section 24",
"correct": "0"
},
{
"ansID": "262",
"ans": "Section 72",
"correct": "1"
},
{
"ansID": "263",
"ans": "Section 27",
"correct": "0"
},
{
"ansID": "264",
"ans": "Section 42",
"correct": "0"
}
]
},
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "66",
"question": "What should you do when your online friends want to meet you?",
"answer": [
{
"ansID": "269",
"ans": "Go ahead, make plans and meet them wherever and whenever they want",
"correct": "0"
},
{
"ansID": "270",
"ans": "Inform your parents and make sure that you meet where there are a lot of people around",
"correct": "1"
},
{
"ansID": "271",
"ans": "Never meet anyone in person that you met online, it’s just not safe",
"correct": "0"
},
{
"ansID": "272",
"ans": "Ignore their request",
"correct": "0"
}
]
},
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "70",
"question": "te",
"answer": [
{
"ansID": "285",
"ans": "tr",
"correct": "1"
},
{
"ansID": "286",
"ans": "tr",
"correct": "0"
},
{
"ansID": "287",
"ans": "tr",
"correct": "0"
},
{
"ansID": "288",
"ans": "tr",
"correct": "0"
}
]
},
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "91",
"question": "When A Player Deliberately Harasses Other Players Within An Online Game, it is known as ",
"answer": [
{
"ansID": "369",
"ans": "Griefing",
"correct": "1"
},
{
"ansID": "370",
"ans": "Spamming",
"correct": "0"
},
{
"ansID": "371",
"ans": "Scamming",
"correct": "0"
},
{
"ansID": "372",
"ans": "Grooming",
"correct": "0"
}
]
},
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "153",
"question": "Which of the following is not a communication channel for a Phisher?",
"answer": [
{
"ansID": "617",
"ans": "Email Account",
"correct": "0"
},
{
"ansID": "618",
"ans": "Instant Messaging",
"correct": "0"
},
{
"ansID": "619",
"ans": "Social Media Account",
"correct": "0"
},
{
"ansID": "620",
"ans": "Search Engine",
"correct": "1"
}
]
}
]
}
I get Successfully response from Server but not store in ArrayList answer value for related question.
My Java Code is,
//Question
static String[] question_id;
static String[] question_type;
static String[] time_required;
static String[] question;
//Answer
static String[] answer_id;
static String[] answer;
static String[] correct;
//Question Array List
static List<String> arr_question_id = new ArrayList<String>();
static List<String> arr_question_type = new ArrayList<String>();
static List<String> arr_time_required = new ArrayList<String>();
static List<String> arr_question = new ArrayList<String>();
//Answer Array List
static List<String> arr_answer_id = new ArrayList<String>();
static List<String> arr_answer = new ArrayList<String>();
static List<String> arr_correct = new ArrayList<String>();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
Url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// Parsing json object response
// response will be a json object
Boolean resultFlag = response.getBoolean("resultFlag");
if (resultFlag == true) {
String success = response.getString("successMessage");
JSONArray json_array_question = response.getJSONArray("Questions");
question_type = new String[json_array_question.length()];
time_required = new String[json_array_question.length()];
question_id = new String[json_array_question.length()];
question = new String[json_array_question.length()];
for (int i = 0; i < json_array_question.length(); i++) {
JSONObject json_object_question = json_array_question.getJSONObject(i);
question_type[i] = json_object_question.getString("questionType");
time_required[i] = json_object_question.getString("timeRequired");
question_id[i] = json_object_question.getString("questionID");
question[i] = json_object_question.getString("question");
JSONArray json_array_answer = json_object_question.getJSONArray("answer");
answer_id = new String[json_array_answer.length()];
answer = new String[json_array_answer.length()];
correct = new String[json_array_answer.length()];
for (int j = 0; j < json_array_answer.length(); j++) {
JSONObject json_object_answer = json_array_answer.getJSONObject(j);
answer_id[j] = json_object_answer.getString("ansID");
answer[j] = json_object_answer.getString("ans");
correct[j] = json_object_answer.getString("correct");
arr_answer_id.add(answer_id[j]);
arr_answer.add(answer[j]);
arr_correct.add(correct[j]);
}
arr_question_type.add(question_type[i]);
arr_time_required.add(time_required[i]);
arr_question_id.add(question_id[i]);
arr_question.add(question[i]);
}
*for (int i = 0; i < arr_question_id.size(); i++) {
item_solo_trivia.setQuestionType(arr_question_type.get(i));
item_solo_trivia.setTimeRequired(arr_time_required.get(i));
item_solo_trivia.setQuestionId(arr_question_id.get(i));
item_solo_trivia.setQuestion(arr_question.get(i));
for (j = 0; j < arr_answer_id.size(); j++) {
item_solo_trivia.setAnswerId(arr_answer_id.get(j));
item_solo_trivia.setAnswer(arr_answer.get(j));
item_solo_trivia.setCorrect(arr_correct.get(j));
}
}*
} else if (resultFlag == false) {
String error = response.getString("errorMessage");
Toast.makeText(activity.getApplicationContext(), error, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(activity,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(activity,
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
Problem with This code, How to Resolve it?
for (int i = 0; i < arr_question_id.size(); i++) {
item_solo_trivia.setQuestionType(arr_question_type.get(i));
item_solo_trivia.setTimeRequired(arr_time_required.get(i));
item_solo_trivia.setQuestionId(arr_question_id.get(i));
item_solo_trivia.setQuestion(arr_question.get(i));
for (j = 0; j < arr_answer_id.size(); j++) {
item_solo_trivia.setAnswerId(arr_answer_id.get(j));
item_solo_trivia.setAnswer(arr_answer.get(j));
item_solo_trivia.setCorrect(arr_correct.get(j));
}
}
And Table is,
//Create Table
public static final String CREATE = "CREATE TABLE IF NOT EXISTS "
+ TABLE
+ " ( "
+ KEY_ID
+ "INTEGER AUTOINCREMENT,"
+ KEY_USER_ID
+ " text not null , "
+ KEY_QUESTION_TYPE
+ " text not null , "
+ KEY_QUESTION_ID
+ " text not null , "
+ KEY_QUESTION
+ " text not null , "
+ KEY_ANSWER_ID_1
+ " text not null , "
+ KEY_ANSWER_ID_2
+ " text not null , "
+ KEY_ANSWER_ID_3
+ " text not null , "
+ KEY_ANSWER_ID_4
+ " text not null , "
+ KEY_ANSWER_1
+ " text not null , "
+ KEY_ANSWER_2
+ " text not null , "
+ KEY_ANSWER_3
+ " text not null , "
+ KEY_ANSWER_4
+ " text not null , "
+ KEY_CORRECT_1
+ " text not null , "
+ KEY_CORRECT_2
+ " text not null , "
+ KEY_CORRECT_3
+ " text not null , "
+ KEY_CORRECT_4 + " text not null" + ");";
How to store Answer list into related Question in SqliteDatabase?
Please Help me and Suggest me.
Thanks.
This question already has answers here:
Parsing json with android
(4 answers)
Closed 8 years ago.
I am trying to parse this json:
[{
"codError": 0,
"msg": "OK"
}, {
"id": 1,
"role": {
"id": 4,
"name": "Super",
"description": "Roling.",
"rights": [],
"superuser": true,
"active": true,
"optimisticLock": 0
},
"now": null,
"points": [],
"firstName": null,
"lastName": null,
"loginName": "admin",
"password": null,
"connected": true,
"active": true,
"optimisticLock": null
},
["U4"]
]
I am not able to get the value of role id and loginName, my code is here:
private static final String TAG_ROLE = "role";
private static final String TAG_ID = "id";
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonarr =new JSONArray(jsonStr);
JSONObject jobj=jsonarr.getJSONObject(1);
JSONObject role =jobj.getJSONObject(TAG_ROLE);
String role_id = role.getString(TAG_ID);
} catch (JSONException e) {
e.printStackTrace();
}
I debug my app and String role_id doesn´t get any value, what is the problem of the code? Thank you
JSONArray array;
array = new JSONArray(jsonStr);
JSONObject obj = array.getJSONObject(1);
JSONObject obj2 = obj.getJSONObject("role");
int id = obj2.getInt("id");
String name = obj2.getString("name");
In case you aren't getting any values, you might want to check if the response is exactly how you're expecting it to be. Also, check the values of TAG_ROLE, TAG_ID.
Edit 1 :
String jsonStr = "[{\n \"codError\": 0,\n \"msg\": \"OK\"\n}, {\n \"id\": 1,\n \"role\": {\n \"id\": 4,\n \"name\": \"Super\",\n \"description\": \"Roling.\",\n \"rights\": [],\n \"superuser\": true,\n \"active\": true,\n \"optimisticLock\": 0\n },\n \"now\": null,\n \"points\": [],\n \"firstName\": null,\n \"lastName\": null,\n \"loginName\": \"admin\",\n \"password\": null,\n \"connected\": true,\n \"active\": true,\n \"optimisticLock\": null\n},\n[\"U4\"]\n\n]";
try {
JSONArray array;
array = new JSONArray(jsonStr);
JSONObject obj = array.getJSONObject(1);
JSONObject obj2 = obj.getJSONObject("role");
int id = obj2.getInt("id");
String name = obj2.getString("name");
System.out.println(id);
System.out.println(name);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have a string from http request and i want to replace multiple chars and strings with others.How i can do this?With Array for more efficient way?
String result =" "hourly": [ {"cloudcover": "0", "humidity": "93", "precipMM": "0.0", "pressure": "1013", "sigHeight_m": "0.7", "swellDir": "70", "swellHeight_m": "0.5", "swellPeriod_secs": "1.0", "tempC": "9", "tempF": "48", "time": "0", "v";
String result2 = result.replace("{", " ");
String result3 = result2.replace("}", " ");
String result4 = result3.replace("[", " ");
String result5 = result4.replace("]", " ");
String result6 = result5.replace("\"", "");
String result7 = result6.replaceAll("......", " ");
String result8 = result7.replaceAll("cloudcover", "\n \ncloudcover");
String result9 = result8.replaceAll("winddir:", " \nwinddir:");
String result10 = result9.replaceAll("tempC:", " \ntempC:");
WeatherInfos.setText( result10 );//Shows the weather info
Try following
String result = "{\"hourly\": [ {\"cloudcover\": \"15\", \"humidity\": \"93\", \"pressure\": \"1013\", \"tempC\": \"9\", \"winddir\": \"25\"}]}";
if(!result.startsWith("{"))
result = "{" + result + "}";
JSONObject JSONResult = new JSONObject(result);
JSONResult = (JSONObject) JSONResult.getJSONArray("hourly").get(0);
String cloudcover = JSONResult.getString("cloudcover");
String tempC= JSONResult.getString("tempC");
String winddir= JSONResult.getString("winddir"); //i do not see winddir in your result
Toast.makeText(getapplicationContext(), "Cloud Cover is "+ cloudcover , Toast.LENGTH_LONG).show();
now print cloudcover, winddir and tempC where ever you want.