Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

304
Views
Get Key and values from JSONObject

I am trying to extract Key and values from my JSONObject. But i am not able to do that. Here is the JSON:

[{"id":["5"]},{"Tech":["Java"]}]

It is a String initially. I have converted that to JSONObject using :

JSONObject jsonObj = new JSONObject("[{"id":["5"]},{"Tech":["Java"]}]");

Then i am trying to get the key and value by:

jsonObj.getString("id");

But its giving me null. Can anyone help me out here?

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Try this:

try {
    JSONArray jsonArr = new JSONArray("[{\"id\":[\"5\"]},{\"Tech\":[\"Java\"]}]");

    for (int i = 0; i < jsonArr.length(); i++) {
        JSONObject jsonObj = jsonArr.getJSONObject(i);
        String k = jsonObj.keys().next();
        Log.i("Info", "Key: " + k + ", value: " + jsonObj.getString(k));
    }

} catch (JSONException ex) {
    ex.printStackTrace();
}
about 4 years ago · Santiago Trujillo Report

0

Parameter you are sending is JsonArray and referring to JsonObject. The Correct way is

JSONObject jsonObj = new JSONObject("{'id':['5','6']},{'Tech':['Java']}");      
    System.out.println(jsonObj.getString("id"));

    JSONArray jsonArray = new JSONArray("[{'id':['5','6','7','8']},{'Tech':['Java']}]");
    System.out.println(jsonArray.length());
    for(int i=0;i<jsonArray.length();i++){
            System.out.println(jsonArray.getJSONObject(i).getString("id"));
    }
about 4 years ago · Santiago Trujillo Report

0

Because at id you dont have a string , you have a array of string ,

so insted of doing this jsonObj.getString("id");

do this

jsonObj.getArray("id"); this will give you that array in return

like if you have a Json Array at id then you have to do this

jsonObj.getJSONArray("id");

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!