How to parse a JSON Array Object? - android

I'm trying to get a JSON array for ListView on Android, but I couldn't so far.
My JSON is like this
[
{
"iD":1,
"name":"name1"
},
{
"iD":2,
"name":"name2"
},
{
"iD":3,
"name":"name3"
},
{
"iD":4,
"name":"name4"
}
]
Also Try tried this second JSON format
{
"userdata":[
{
"iD":1,
"name":"name1"
},
{
"iD":2,
"name":"name2"
},
{
"iD":3,
"name":"name3"
},
{
"iD":4,
"name":"name4"
}
]
}
And my Java looks like
private void loadIntoListView(String json) throws JSONException {
Log.e("log1 = ", json);
JSONArray jsonArray = new JSONArray(json);
Log.e("log2 = ","5" ); //Integer.toString(jsonArray.length())
String[] heroes = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
heroes[i] = obj.getString("name");
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
listView.setAdapter(arrayAdapter);
}
private void loadIntoListView(String json) throws JSONException {
Log.e("result 2 = ", json);
JSONObject entries = new JSONObject(json);
JSONArray jsonArray = entries.getJSONArray("userdata");
Log.e("length = ","5" ); //Integer.toString(jsonArray.length())
String[] heroes = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
heroes[i] = obj.getString("name");
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
listView.setAdapter(arrayAdapter);
}
I see the first log, but I can't see second. Also, I can't get the names for ListView.
require_once('connection.php');
$heroes = array();
$sql = "SELECT iD, name FROM valTable;";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $name);
while($stmt->fetch()){
$temp = [
'iD'=>$id,
'name'=>$name
];
array_push($heroes, $temp);
}
echo json_encode($heroes);

You should use a JSON library such as Gson to parse those objects for your.
Add on your gradle dependencies
implementation 'com.google.code.gson:gson:2.8.5'
You can create objects like
data class JsonRootObject(val userdata: List<User>)
data class User(val iD:Int, val name:String)
And then parse your object
val myParsedObject = Gson().fromJson(jsonString, JsonRootObject::class.java);
Make sure that your field names are the same as your object being parsed, this also means case sensitive. If you want to change their mapping name you might want to use #SerializedName("id") annotation like
class User {
#SerializedName("id")
lateinit var id: Int
#SerializedName("my_name")
lateinit var name: String
}
Consider this answer to your second object
{
"userdata":[
{
"iD":1,
"name":"name1"
},
{
"iD":2,
"name":"name2"
},
{
"iD":3,
"name":"name3"
},
{
"iD":4,
"name":"name4"
}
]
}
and of course, all this is written in Kotlin.

Use try catch instead of throws
try {
JSONArray jsonArray = new JSONArray(json);
Log.e("log2 = ", "5"); //Integer.toString(jsonArray.length())
String[] heroes = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
heroes[i] = obj.getString("name");
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
listView.setAdapter(arrayAdapter);
}
catch (Exception e)
{
Log.e("log3 = ", ""+e);
}

Try first to convert your String json to JSONObject and then convert that JSONObject to JSONArray. See this answer.

Related

How to get json object and array values?

How to parse JSON values in this format? I want to get the details of the data element but inside data there are 'dates' and inside dates there is array containing two more elements. I want to get all the dates first inside data and then within these dates I want all the information within these dates. How can I achieve this? Please Help. I tried with below code but it hasn't worked
try {
JSONObject jsonObject = new JSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
JSONArray session;
for (int i = 0; i < jsonArray.length() - 1; i++) {
jsonObject = jsonArray.getJSONObject(i);
session= jsonObject.getJSONArray("session");
Log.d("MyLog", session + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
Following is the format
{
"status": 1,
"status_code": 200,
"data": {
"2018-02-11": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
],
"2018-02-12": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
]
}
}
You just need to pass the response string to the method. You can try this:
private void jsonParsing(String jsonString) {
// String jsonString = "{ \"status\": 1, \"status_code\": 200, \"data\": { \"2018-02-11\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ], \"2018-02-12\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ] } }";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Log.e(TAG, "jsonParsing: "+iter );
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> sessions = new ArrayList<String>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject = datesArray.getJSONObject(i);
sessions.add(datesObject.getString("session"));
}
Log.d("MyLog", sessions + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
(1) get JSONObject of Main json
JSONObject objMain = new JSONObject("your json string");
(2)get JSONObject of "data" from main json
JSONObject jsonData = objMain.getJSONObject("data")
(3) get all keys (dates) from object "data"
Iterator<String> iter = jsonData.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONArray arrayDate = objData.getJSONArray(key)
for (i = 0; i < arrayDate.length(); i++) {
JSONObject objDate = arrayDate.getJSONObject(i)
Log.d("#session :", "" + objDate.getString("session"))
Log.d("#place :", "" + objDate.getBoolean("place"))
}
} catch (JSONException e) {
// Something went wrong!
}
}
try this one code
IN THIS CODE jsonMstObject IS TEMP OBJECT YOU HAVE TO USE YOUR API RESPONSE JSONobject INSTEAD OF jsonMstObject
try {
JSONObject jsonMstObject = new JSONObject("{"status":1,"status_code":200,"data":{"2018-02-11":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}],"2018-02-12":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}]}}");
JSONObject jsonObject = jsonMstObject.getJSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
ArrayList<String> arrSession = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
arrSession.add(jsonObject.getString("session"));
}
Log.d("MyLog", arrSession + "");
} catch (JSONException e) {
e.printStackTrace();
}
in this code arrSession is your session string array
Ex. you passed cuurentdate = "2018-02-11" then you recived result like
[01:00 AM, 02:00 AM]
Note: this code is worked based on your cuurentdate param. This is code for get static date array from data and create String Array.

just only one list on my listview

I have array look like this :
"results":[
{
"code":"jne",
"name":"Jalur Nugraha Ekakurir (JNE)",
"costs":[
{
"service":"OKE",
"description":"Ongkos Kirim Ekonomis",
"cost":[
{
"value":38000,
"etd":"4-5",
"note":""
}
]
},
{
"service":"REG",
"description":"Layanan Reguler",
"cost":[
{
"value":44000,
"etd":"2-3",
"note":""
}
]
},
{
"service":"SPS",
"description":"Super Speed",
"cost":[
{
"value":349000,
"etd":"",
"note":""
}
]
},
{
"service":"YES",
"description":"Yakin Esok Sampai",
"cost":[
{
"value":98000,
"etd":"1-1",
"note":""
}
]
}
]
}
]
My code on android to process array, problem in my code on function "for" before I copy and edit another code from file :
JSONObject jsonObjsko = new JSONObject(rajaongkir);
String resultse = jsonObjsko.getString("results");
JSONArray jsonObjssto = new JSONArray(resultse);
JSONObject mJsonObject = jsonObjssto.getJSONObject(0);
costs = mJsonObject.getString("costs");
JSONArray jsonArray = new JSONArray(costs);
for (int k = 0; k < jsonArray.length(); k++) {
try {
JSONArray jsonArrayp = new JSONArray(costs);
JSONObject jsonObject = jsonArrayp.getJSONObject(k);
String serviceq = jsonObject.getString("cost");
String servicel = jsonObject.getString("service");
kon = String.valueOf(jsonArray.length());
kin = kin + k;
JSONArray jsonObjsstorng = new JSONArray(serviceq);
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
String values = mJsonObjectrng.getString("value");
ShipPerActiv wp = new ShipPerActiv(servicel, values);
arraylist.add(wp);
}
catch (JSONException e) {
e.printStackTrace();
}
}
This code for ShipPerActiv for add arraylist :
public class ShipPerActiv {
private String services;
private String hongkir;
public ShipPerActiv(String services,String hongkir) {
this.services = services;
this.hongkir = hongkir;
}
public String getservices() {return this.services; }
public String gethongkir() {return this.hongkir; }
}
I tried use harddebug with kon & kin true function for normal but not on my listview just one int(0) not int(1)~etc
At first convert your StringObject to JSONObject and dont forget to add { at first of string and } to end of string:
JSONObject parentObject = new JSONObject("{"+"JsonString"+"}");
Then parse your object like this :
try {
JSONObject parentObject = new JSONObject(a);
JSONArray results = parentObject.getJSONArray("results");
JSONObject resultsObject=results.getJSONObject(0);
JSONArray costsArray = resultsObject.getJSONArray("costs");
for (int i = 0; i < costsArray.length(); i++) {
Log.d("CostsJsonObject" , costsArray.getJSONObject(i).toString());
}
} catch (JSONException e) {
Log.d("CostsJsonObject Exception" , e.toString());
}
And result :
I think your problem is on this code :
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
Simply change it to :
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(0);
Hope it'll help you ;)

Unable to parse JsonArray inside JsonArray

Hi i was trying to parse a json array inside another json array. Help me with this.
my Json Array is
"results":[
{
"percentcompleted":0,
"requirers":[
{
"activityContext":null,
"auditReason":null,
"assignee":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"targetDate":null,
"assignment":{
"id":"stcur000000000003182",
"displayName":null
},
"learningEvent":{
"id":"curra000000000003001",
"displayName":"Studieplan_test för OKQ8"
},
"jobTypeId":null,
"listIds":null,
"assignedOn":1502084325000,
"source":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"required":true,
"actions":null,
"id":"currh000000000014343"
}
],
"basicdetail":{
"revokedOn":null,
"need_recert":false,
"curriculum":{
"id":"curra000000000003001",
"displayName":"Studieplan_test för OKQ8"
},
"recert_window_starts_on":null,
"createdBy":"vrao",
"updatedBy":"vrao",
"createdOn":1502084325000,
"updatedOn":1508357353000,
"status":{
"intStatus":400,
"description":"Assigned",
"displayName":"Assigned"
},
"type":"CURRICULUM",
"path":{
"id":"track000000000003081",
"displayName":"Studieplan"
},
"acquiredOn":null,
"assignee":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"targetDate":null,
"startedOn":null,
"assignedOnDate":1502084325000,
"heldCertNo":"00003787",
"owner":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"id":"stcur000000000003182",
"assigneeAdditionalDetails":{
"person_no":"VRAO",
"username":"VRAO"
}
},
"isgranted":null
},
and my Code to parse the above data is
public class CurriculaParser {
public ArrayList<CurriculaData> getData(String response)
{
ArrayList<CurriculaData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("results");
CurriculaData data;
for(int i = 0;i<array.length();i++)
{
data = new CurriculaData();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requires");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
JSONObject innerObj = reqObj.getJSONObject("learningEvent");
data.setTitle(innerObj.getString("displayName"));
data.setAssignedOn(reqObj.getString("assignedOn"));
}
JSONArray basicDetailArray = resObj.getJSONArray("basicdetail");
for(int k=0;k<basicDetailArray.length();k++) {
JSONObject basicDetailObj = basicDetailArray.getJSONObject(k);
JSONObject statusObj = basicDetailObj.getJSONObject("status");
data.setStatus(statusObj.getString("displayName"));
data.setAcquiredOn(basicDetailObj.getString("acquiredOn"));
JSONObject assignObj = basicDetailObj.getJSONObject("assignee");
data.setAssignedBy(assignObj.getString("displayName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
and finally i got error like
org.json.JSONException: No value for requires
let me know the error what i made and iam a beginner in dealing with jsonarray inside another jsonarray
org.json.JSONException: No value for requires
JSONException
KEY mismatches on lookups
You should pass requirers instead of requires.
JSONArray reqArray = resObj.getJSONArray("requirers");
fixed the requires TYPO error
public class CurriculaParser {
public ArrayList<CurriculaData> getData(String response)
{
ArrayList<CurriculaData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("results");
CurriculaData data;
for(int i = 0;i<array.length();i++)
{
data = new CurriculaData();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requirers");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
JSONObject innerObj = reqObj.getJSONObject("learningEvent");
data.setTitle(innerObj.getString("displayName"));
data.setAssignedOn(reqObj.getString("assignedOn"));
}
JSONArray basicDetailArray = resObj.getJSONArray("basicdetail");
for(int k=0;k<basicDetailArray.length();k++) {
JSONObject basicDetailObj = basicDetailArray.getJSONObject(k);
JSONObject statusObj = basicDetailObj.getJSONObject("status");
data.setStatus(statusObj.getString("displayName"));
data.setAcquiredOn(basicDetailObj.getString("acquiredOn"));
JSONObject assignObj = basicDetailObj.getJSONObject("assignee");
data.setAssignedBy(assignObj.getString("displayName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}

nested JSON object inside JSON array

I'm trying to parse a JSON object. The JSON response is as follows.
{
"message": "Success",
"list": [
{
"orderId": 24,
"phoneNumber": "1234567893",
"totalAmount": 100,
"addressBean": {
"cadId": 1,
"phone2": "1234567899",
"address1": "34, gandhi nagar",
}
},
Android code which i have tried for getting "orderId", "phoneNumber" and "totalAmount" is below.
final List<OrderModel> orderList = new ArrayList<>();
public void onResponse(JSONObject response) {
try {
if (response.getString("message").equalsIgnoreCase("Success")) {
JSONArray jArray = response.getJSONArray("list");
for (int i = 0; i < jArray.length(); i++) {
OrderModel model = new OrderModel();
orderModel.setOrderId(jArray.getJSONObject(i).getString("orderId"));
orderModel.setphoneNumber(jArray.getJSONObject(i).getString("phoneNumber"));
orderModel.setTotalAmount(new BigDecimal(jArray.getJSONObject(i).getString("totalAmount")));
orderList.add(orderModel);
}
setOrderList(orderList);
I want to show the "cadId", "phone2" and "address1" in a Textview. How can i do that?
Try to use this Code
try {
JSONArray jArray = response.getJSONArray("list");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
if (jsonObject.has("addressBean")){
JSONObject addressObject = jsonObject.getJSONObject("addressBean");
int cadId = addressObject.getInt("cadId");
String phone = addressObject.getString("phone2");
String address = addressObject.getString("address1");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Code for phone2
String phone2 = jArray.getJSONObject(i).getJSONObject("addressBean").getString("phone2");
Use getInt() for cadId

How do I pull the string array from this json object?

I am trying to get a list of available numbers from the following json object, using the class from org.json
{
"response":true,
"state":1,
"data":
{
"CALLERID":"81101099",
"numbers":
[
"21344111","21772917",
"28511113","29274472",
"29843999","29845591",
"30870001","30870089",
"30870090","30870091"
]
}
}
My first steps were, after receiving the json object from the web service:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
Now, how do I save the string array of numbers?
use:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
JSONArray arrJson = jsonData.getJSONArray("numbers");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++)
arr[i] = arrJson.getString(i);
you need to use JSONArray to pull data in an array
JSONObject jObj= new JSONObject(your_json_response);
JSONArray array = jObj.getJSONArray("data");
Assuming that you are trying to get it in a javascript block, Try something like this
var arrNumber = jsonData.numbers;
My code is for getting "data":
public void jsonParserArray(String json) {
String [] resultsNumbers = new String[100];
try {
JSONObject jsonObjectGetData = new JSONObject(json);
JSONObject jsonObjectGetNumbers = jsonObjectGetData.optJSONObject("results");
JSONArray jsonArray = jsonObjectGetNumbers.getJSONArray("numbers");
for (int i = 0; i < jsonArray.length(); i++) {
resultsNumbers[i] = jsonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, e.toString());
}
}

Categories

Resources