Tugrul
Tugrul

Reputation: 31

How to parse a JSON Array Object?

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

Upvotes: 0

Views: 388

Answers (3)

Victor Oliveira
Victor Oliveira

Reputation: 3713

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.

Upvotes: 2

faranjit
faranjit

Reputation: 1627

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

Upvotes: 0

Athira
Athira

Reputation: 1213

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

Upvotes: 0

Related Questions