json data without array name - android

This is my array which I retrieve from a url
[{"ash_id":"1","asg_code":"1226","ash_name":"hello","ash_cell":"123","ash_nic":"123","ash_long":"34.015","ash_lat":"71.5805","zm_id":null,"created_by":"0","created_date":"0000-00-00
00:00:00","last_updated":"2016-08-29 07:52:35"}]
I have array without array name, I can read data if there is name of jason array but I am unable to do that with this type of array.
any suggestion my code for json with array name
String json = serviceClient.makeServiceCall(URL_ITEMS, ServiceHandler.GET);
// print the json response in the log
Log.d("Get match fixture resps", "> " + json);
if (json != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
Log.d("json aray", "user point array");
int len = matchFixture.length();
Log.d("len", "get array length");
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
Double matchId = Double.parseDouble(c.getString(TAG_MATCHID));
Log.d("matchId", String.valueOf(matchId));
Double teamA = Double.valueOf(c.getString(TAG_TEAMA));
Log.d("teamA", String.valueOf(teamA));
String teamB = c.getString(TAG_TEAMB);
Log.d("teamB", teamB);`

List<Double> listMatch = new ArrayList<Double>();
List<Double> listA = new ArrayList<Double>();
List<String> listB = new ArrayList<String>();
Create three arrayList and add data in that list
if(json!=null)
{
try {
Log.d("try", "in the try");
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
listMatch.add(Double.parseDouble(c.getString(TAG_MATCHID)));
Log.d("matchId", String.valueOf(matchId));
listA.add(Double.valueOf(c.getString(TAG_TEAMA));
Log.d("teamA", String.valueOf(teamA));
listB.add(c.getString(TAG_TEAMB);
Log.d("teamB", teamB);
}
} catch (JSONException e) {
e.printStackTrace();
}
}

directly pass jsonarray string to JSONArray object constructor.
String json = [{"ash_id":"1","asg_code":"1226","ash_name":"hello","ash_cell":"123","ash_nic":"123","ash_long":"34.015","ash_lat":"71.5805","zm_id":null,"created_by":"0","created_date":"0000-00-00 00:00:00","last_updated":"2016-08-29 07:52:35"}];
JSONArray array = new JSONArray(json);

You can directly pass the JSON response from the URL to the json if it is dynamic. Use something like this:
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String id = jsonobject.getString("ash_id");
String code = jsonobject.getString("ash_code");
String name = jsonobject.getString("ash_name");
String cell = jsonobject.getString("ash_cell");
String nic = jsonobject.getString("ash_nic");
String lng = jsonobject.getString("ash_long");
String lat = jsonobject.getString("ash_lat");
String zm_id = jsonobject.getString("zm_id");
String created_by = jsonobject.getString("created_by");
String created_date = jsonobject.getString("created_date");
String updated_date = jsonobject.getString("last_updated");
}
This will update your data, as long as the node names remain the same.
That's all :)

This code worked for me:
public class MainActivity extends AppCompatActivity {
private TextView textView;
private RequestQueue queue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view_result);
Button buttonParse = findViewById(R.id.button_parse);
queue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse() {
String url = "http://10.216.70.19:8080/restServices/webapi/services/getAGVStatusList"; //This is my Json url
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//weatherData.setText("Response is :- ");
parseData(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("Data Not Received");
}
});
queue.add(request);
super.onStart();
}
private void parseData(String response) {
try {
// Create JSOn Object
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <jsonArray.length() ; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
textView.setText(jsonObject.getString("batteryLevel")); //get the desired information from the Json object
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Related

Android parse json from multiple url

I can parse json from an url in this way:
String link1 = "http://www.url.com/test1.json";
String link2 = "http://www.url.com/test2.json";
private void fetchMovies() {
String url = link1;
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
Movie m = new Movie(rank, title);
movieList.add(0, m);
} catch (JSONException e) {
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
I want to parse my json from multiple url.
I want to parse url1 and url2 at the same time.
How can I do that?
Why don't you use "links" as array ?
In case you will use an array:
JSONObject jsonObject = new JSONObject();
JSONArray keys = jsonObject.getJSONArray("links");
int length = keys.length();
for (int i = 0; i < length; i++) {
new ReadJSON().execute(keys.getString(i));
}
Anyway, you take all the keys and go one after the other, and then query each
EDIT:
JSONObject jsonObject = new JSONObject(/*Your links json*/);
JSONObject links = jsonObject.get("links");
Iterator<String> keys = links.keys();
while (keys.hasNext()) {
new ReadJSON().execute(links.getString(keys.next()));
}

Access Nested JSON Android

I want to know how do I access the values of this JSON in Android:
{
"dados": [{
"Id": 3,
"IdChamado": 3,
"Chamado": "value",
"Solicitante": "value",
"Acao": "",
"ItemDeCatalogo": "Mobile | Instalação",
"InicioPrevisto": "06/01/2017 08:11:00",
"TerminoPrevisto": "06/01/2017 08:22:00"
}, {
"Id": 4,
"IdChamado": 4,
"Chamado": "value",
"Solicitante": "value",
"Acao": "",
"ItemDeCatalogo": "value",
"InicioPrevisto": "06/01/2017 08:11:34",
"TerminoPrevisto": "06/01/2017 08:11:34"
}],
"success": true,
"erroAplicacao": false
}
I need to access the values "IdChamado", "chamado", "Solicitante", for example. I've seen nested arrays answers but with jsonObjects having an actual name, like this .
PS: I'm sorry I forgot to post my codes:
//Method called when the doInBack is complete
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jArray = jsonObject.getJSONArray("dados");
Log.i("***2nd JSON ITSELF***", result);
for (int i=0; i<jArray.length(); i++) {
JSONObject jsonPart = jArray.getJSONObject(i);
int id = jsonPart.getInt("id");
Log.i("***id***", String.valueOf(id));
String chamado = jsonPart.getString("Chamado");
Log.i("***Chamado***", chamado);
String solicitante = jsonPart.getString("solicitante");
Log.i("***Solicitante***", solicitante);
String itemDeCatalogo = jsonPart.getString("itemDeCatalogo");
Log.i("***Item de Catalogo***", itemDeCatalogo);
}
}catch(JSONException e) {
e.printStackTrace();
}// END CATCH
}// END POST EXECUTE
[SOLVED]: Thank you so much people, you are the reason I like to code (Not be afraid of asking stupid questions). It all worked well with the codes you sent as answer. I thought it would be more complicated. xD
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonobject = new JSONObject(result);
JSONArray jsonarray = jsonobject.getJSONArray("dados");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jobject = jsonarray.getJSONObject(i);
String idChamado = jobject.getString("IdChamado");
String solicitante = jobject.getString("Solicitante");
Log.i("**id**", idChamado);
Log.i("**solicitante**", solicitante);
}
}catch(JSONException e) {
e.printStackTrace();
}// END CATCH
}// END POST EXECUTE
JSONObject jsonobject = new JSONObject("your JSON String here");
JSONArray jsonarray = jsonobject.getJSONArray("dados");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String IdChamado = jsonobject.getString("IdChamado");
String Solicitante = jsonobject.getString("Solicitante");
}
please try this
try this:
try{
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONArray("dados");
for(int i=0;i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String IdChamado = object.getString("IdChamado");
String Chamado = object.getString("Chamado");
//rest of the strings..
}
}
catch (JSONException e){
e.printStackTrace();
}
Try this
for (int i=0; i<jArray.length(); i++) {
JSONObject jsonobject = jArray.getJSONObject(i);
int IdChamado = jsonobject.getInt("IdChamado"); //idchamado here
String chamado = jsonobject.getString("Chamado");
String solicitante = jsonobject.getString("Solicitante");
}
Use the correct keys while opting any data
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jArray = jsonObject.getJSONArray("dados");
Log.i("***2nd JSON ITSELF***", result);
for (int i=0; i<jArray.length(); i++) {
JSONObject jsonObject = new JSONObject(result);
JSONArray jArray = jsonObject.optJSONArray("dados");
Log.i("***2nd JSON ITSELF***", result);
for (int i=0; i<jArray.length(); i++) {
JSONObject jsonPart = jArray.optJSONObject(i);
int id = jsonPart.optInt("Id");
Log.i("***id***", String.valueOf(id));
String chamado = jsonPart.optString("Chamado");
Log.i("***Chamado***", chamado);
String solicitante = jsonPart.optString("Solicitante");
Log.i("***Solicitante***", solicitante);
String itemDeCatalogo = jsonPart.optString("ItemDeCatalogo");
Log.i("***Item de Catalogo***", itemDeCatalogo);
}
}catch(JSONException e) {
e.printStackTrace();
}// END CATCH
}
I wrote a library for parsing and generating JSON in Android
http://github.com/amirdew/JSON
for your sample:
JSON jsonData = new JSON(jsonString);
//access IdChamado of first item:
int IdChamado = jsonData.key("dados").index(0).key("IdChamado").intValue();
//in loop:
JSON dadosList = jsonData.key("dados");
for(int i=0; i<dadosList.count(); i++){
int IdChamado = dadosList.index(i).key("IdChamado").intValue();
String Chamado = dadosList.index(i).key("Chamado").stringValue();
}

Having issue while parsing Json volley request

this is my request code ,please help me to parse it correctly. I want all the options for each particular question but I am getting only one option .can anyone solve it. I have attached SS of my data format.
JsonObjectRequest request = new JsonObjectRequest(
"http://www.proprofs.com/quiz-school/mobileData/request.php?request=QuizStart&module=handShake&title=does-your-crush-like-you-girls-only_1",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
// ArrayList<Data> listData = new ArrayList<>();
if (response != null && response.length() > 0) {
try {
JSONArray array = response.getJSONArray("quiz");
// JSONObject jsonObject = array.getJSONObject(0);
for (int i = 0; i < array.length(); i++) {
JSONObject currentArray = array.getJSONObject(i);
DataQuestions movie = new DataQuestions();
movie.setQuestion(currentArray.getString("question"));
String question = currentArray.getString("question");
System.out.println("question----------" + question);
movie.setQuesImage(currentArray.getString("QuesImage"));
String image = currentArray.getString("QuesImage");
System.out.println("QuesImage----------" + image);
JSONArray keys= currentArray.getJSONArray("keys");
for(int j =0;j<keys.length();j++){
JSONObject keyobject = keys.getJSONObject(j);
movie.setOption(keyobject.getString("option"));}
/*String key = null;
if(keys.getJSONObject("option")) {
key = keys.getString("option");
}
movie.setOption(key);*/
/* JSONArray jsonArray1 = (jsonObject.getJSONArray("keys"));
int numberOfItemsInResp = jsonArray1.length();
for (int j = 0; j < numberOfItemsInResp; j++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(j);
DataQuestions options = new DataQuestions();
// movie = new DataQuestions();
options.setOption(jsonObject2.getString("option"));
String optios = jsonObject2.getString("option");
System.out.println("option----------" + options);
// JSONArray jsonArray1 = (response.getJSONArray("keys"));*/
movieList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
Toast.makeText(MainActivity.this, "No Items Available", Toast.LENGTH_LONG).show();
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(request);
}
This is because, you use a single object in second for loop. You should to define keys object and stored within arraylist in main object. Like this
public class Quiz {
String quizId;
String QuesImage;
String question;
String questionId;
String Type;
int index;
ArrayList<Keys> keysList;
}
public class Keys{
String answerId;
String option;
String AnsImage;
}
and parse it
JSONArray array = response.getJSONArray("quiz");
for (int i = 0; i < array.length(); i++){
JSONObject jsonObj = array.getJSONObject(i);
Quiz quiz = new Quiz();
quiz.QuesImage = jsonObj.getString("QuesImage");
quiz.question = jsonObj.getString("question");
quiz.questionId = jsonObj.getString("questionId");
quiz.Type = jsonObj.getString("Type");
quiz.index = jsonObj.getInt("index");
JSONArray keys = jsonObj.getJSONArray("keys");
for (int j = 0; j < keys.length(); j++) {
JSONObject keysObj = keys.getJSONObject(j);
Keys keys = new Keys();
keys.answerId = keysObj.getString("answerId");
keys.option = keysObj.getString("option");
keys.AnsImage = keysObj.getString("AnsImage");
quiz.keysList.add(keys);
}
}

how to parse json object and json array in listview android

I am beginner to android app. I am facing trouble how to parse json object and json array to listview in android. Here is my json output
UPDATED WITH JSON CORRECTION
{status: "ok", listUsers: [{"id":2,"username":"myusername","name":"myname","email":"myemail","password":"mypassword","groupid":1,"type":"mytype"},{"id":3,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"},{"id":4,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":5,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":6,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":7,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":8,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":9,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":10,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":11,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"1"},{"id":12,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":13,"username":"yuwah","name":"yu","email":"mail#gmail.com","password":"pass1","groupid":1,"type":"type1"},{"id":14,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"}] }
Can anyone explain me how to do it. I am searching all over the topics but I still can't get it. Thanks.
Here is my code block
public class MainActivity extends ListActivity {
String url = "http://staging.workberryplus.com/mobile/listUsers/1";
ProgressDialog PD;
ArrayList<String> listUsers;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listUsers = new ArrayList<String>();
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
adapter = new ArrayAdapter(this, R.layout.items, R.id.tv, listUsers);
setListAdapter(adapter);
MakeJsonArrayReq();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
private void MakeJsonArrayReq() {
PD.show();
//JsonArrayRequest jr=new JsonArrayRequest(url, listener, errorListener)
final StringRequest jreq = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
for (int i = 0; i < response.length(); i++) {
try {
Log.d("Response","->"+response);
JSONObject jo = new JSONObject(response);
JSONArray jarray = jo.getJSONArray("listUsers");
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
PD.dismiss();
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MyApplication.getInstance().addToReqQueue(jreq, "jreq");
}
}
try {
JSONObject jo = new JSONObject(response);
JSONArray jarray =jo.getJSONArray("listUsers");
for (int i = 0; i < jarray.length(); i++){
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
Convert your String which is response to Json Object
JSONObject jsonObj = new JSONObject(response);
Then do the following
try {
if (jsonObj != null) {
if (jsonObj.optString("status").equals("ok")) {
JSONArray jsonArray = jsonObj.optJSONArray("listUsers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if (jsonObject != null) {
//Do work here
}
}
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
try this and make changes accordingly and let me know if it work for you or not
JSONObject jo2 = jarray.getJSONObject(i);
You are iterating over the length of the response (a string). You should iterate over the length of jarray

could not be able to get data from json webservice

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);
}
}
}

Categories

Resources