Get some data from JSON - android

I need some help with JSON. I get a JSON as follows:
{
"1": {
"id": "1",
"position": "1",
"Category": {
"id": "1",
"position": "1",
"created_at": "2012-10-24 15:42:47",
"updated_at": "2012-11-13 13:46:25",
"name": "ABCD"
}
}
}
and I want to get all data from field Category.
I try this way:
JSONObject categoryObject = json.getJSONObject("Category");
but I get error:
no value for Category. How I can get data for Category field?

JSONObject categoryObject = json.getJSONObject("1").getJSONObject("Category");
categoryObject.get("id"); // return 1
categoryObject.get("position"); // return 1
categoryObject.get("name"); // return "ABCD"
etc

You should to do folowing.
JSONObject json1 = json.getJSONObject("1");
JSONObject categoryObject = json1.getJSONObject("Category");
You can see hierarhy on the site

try {
String jsonString="{\"1\":{\"id\":\"1\",\"position\":\"1\",\"Category\":{\"id\":\"1\",\"position\":\"1\",\"created_at\":\"2012-10-24 15:42:47\",\"updated_at\":\"2012-11-13 13:46:25\",\"name\":\"ABCD\"}}}";
JSONObject jsonObject=new JSONObject(jsonString);
JSONObject jsonObject1= jsonObject.getJSONObject("1");
String id=jsonObject1.getString("id");
String position =jsonObject1.getString("position");
JSONObject jsonObjectCategory= jsonObject1.getJSONObject("Category");
String idCategory=jsonObjectCategory.getString("id");
String positionCategory=jsonObjectCategory.getString("position");
String createdAt=jsonObjectCategory.getString("created_at");
String updatedAt=jsonObjectCategory.getString("updated_at");
String name=jsonObjectCategory.getString("name");
Log.e(getClass().getSimpleName(), "name="+name +"; created_at= "+createdAt);
} catch (JSONException e) {
e.printStackTrace();
}

Related

Error while parsing JSON Object in Java Android

In my Android app, I am fetching the details of Points table of a tournament to convert the output to a string from JSON object to Java
JSON object is shown below:
{
"group": {
"Teams": [
{
"name": "Team 1",
"p": "10",
"w": "9",
"l": "1",
"points": "18"
},
{
"name": "Team 2",
"p": "10",
"w": "9",
"l": "1",
"points": "18"
},
{
"name": "Team 3",
"p": "10",
"w": "9",
"l": "1",
"points": "18"
},
{
"name": "Team 4",
"p": "10",
"w": "6",
"l": "4",
"points": "12"
},
{
"name": "Team 5",
"p": "10",
"w": "6",
"l": "4",
"points": "12"
},
{
"name": "Team 6",
"p": "10",
"w": "6",
"l": "4",
"points": "12"
},
{
"name": "Team 7",
"p": "10",
"w": "5",
"l": "5",
"points": "11"
},
{
"name": "Team 8",
"p": "10",
"w": "5",
"l": "5",
"points": "11"
}
]
}
}
Android Java Code is below:
JSONObject match = new JSONObject(response);
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (match.has("Teams")) {
JSONObject teams = group.getJSONObject("Teams");
if (teams.has("0")) {
JSONObject teams_object = teams.getJSONObject("0");
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
}
But I am getting the error where I print the error message through getMessage() method. Here is the error below:
Error: Value ["name","p","w","l","points"] at header of type org.json.JSONArray cannot be converted to JSONObject
Can anyone please help like where I am going wrong or what is the fix ? Thanks in advance
In your Json Teams holds the Array of Object and you are parsing wrong.
Try this
JSONObject jsonObject = new JSONObject(response);
JSONObject groups = jsonObject.getJSONObject("group");
JSONArray teams = groups.getJSONArray("Teams");
for(int i=0;i<teams.length();i++){
JSONObject obj = teams.getJSONObject(i);
name.append(obj.getString("name")+"\n");
}
There is 4 mistakes in your code,
1.You have to check whether group has teams instead match has teams.
2.You have to get team as JSONArray instead of JSONObject because it is array.
3.You have to check the size of team, instead of find the object with key 0, there is no object with name 0 in your group,
4.You have to get the object based on index instead of key(ie., 0)
Please check the working code, this is tested
try {
JSONObject match = new JSONObject(response);
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (group.has("Teams")) {
JSONArray teams = group.getJSONArray("Teams");
if (teams.length() > 0) {
JSONObject teams_object =(JSONObject) teams.get(0);
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
Log.v(TAG, team_name);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONObject subObject = jsonObject.getJSONObject("group") ;
JSONArray jsonArray = subObject.getJSONArray("Teams");
for (int i=0; i<jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
String p= jsonObject.getString("p");
String w= jsonObject.getString("w");
String l= jsonObject.getString("l");
String points = jsonObject.getString("points");
}
} catch (Exception e) {
e.printStackTrace();
}
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (match.has("Teams")) {
JSONArray teams = group.getJSONArray("Teams");
// for only 0th element use below code else looping
JSONObject teams_object = (JSONObject) teams.get(0);
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
Error: Value ["name","p","w","l","points"] at header of type
org.json.JSONArray cannot be converted to JSONObject
You are getting the error because there is an Array of Teams and you are trying parse with JSONObject
Please check below code snippet. It will work.
try {
JSONObject match = new JSONObject("your_response");
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (group.has("Teams")) {
JSONArray teams = group.getJSONArray("Teams");
for(int i=0; i < teams.length(); i++){
JSONObject teams_object = (JSONObject) teams.get(i);
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this #SaAsh, I have just edited by taking your answer
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (match.has("Teams")) {
JSONObject teams = group.getJsonArray("Teams");
for(int i = 0 ; i < teams.length();i++){
JSONObject teams_object = teams.getJSONObject("i");
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
}
}

Android - Getting value from the JSON object

I have this json
{
"results": [
{
"user": {
"gender": "male",
"name": {
"title": "mr",
"first": "herbert",
"last": "davidson"
},
"location": {
"street": "9763 fincher rd",
"city": "melbourne",
"state": "new south wales",
"zip": 26278
},
"email": "herbert.davidson#example.com",
"username": "lazyelephant581",
"password": "abgrtyu",
"salt": "O8ZbSsUL",
"md5": "7575bd959be09bc6d510a6a91750ce40",
"sha1": "0db99de8402e1defbd7935dbd602d99329698d4d",
"sha256": "c283d262115f90b729bb555db3dbecc8d27eebed513d7f01da799dec9e9d3269",
"registered": 1275070071,
"dob": 122409280,
"phone": "05-5742-3228",
"cell": "0481-652-548",
"TFN": "973720989",
"picture": {
"large": "https://randomuser.me/api/portraits/men/24.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/24.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/24.jpg"
}
}
}
],
"nationality": "AU",
"seed": "0a69317ece7072e000",
"version": "0.7"
}
and im doing this:(result is the json returned from the service)
try{
JSONObject jsonResponse = new JSONObject(result);
JSONObject jo = jsonResponse.getJSONObject("user");
String nome = jo.getString("username");
}catch(Exception e) {
e.printStackTrace();
}
but gives me this error
org.json.JSONException: No value for username
What im doing wrong? I tryed to do a JSONArray, tryed to get the jsonobject from another jsonobject, but giver an error that cannot convert jsonobject to a jsonarray.
regards!
Rafael
Try this in your code .
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray results = jsonObject.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject jo = results.getJSONObject(i);
JSONObject user = jo.getJSONObject("user");
String username = user.optString("username");
}
} catch (JSONException e) {
e.printStackTrace();
}
Use optString in your code .If your username is null,it will not return error .
The first-level key in your dictionary is "results", not "user". Also, results is an array, so you have to index into that.
You're trying to access: user->username
You need to access: results[0]->user->username

Reading data from a json file in Android and put it in an array

if i have a json file like that
{
"users": [{
"name": "aa",
"address": "a"
},
{
"name ": "bb",
"address": "b"
},
{
"name": "cc",
"address": "c"
},
]}
how to read this json file and put all names in a String array in android
i used this code but in second loop it catches exception
public void loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
}
try {
JSONObject obj = new JSONObject(json);
JSONArray m_jArry = obj.getJSONArray("users");
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
names.add(jo_inside.getString("name"));
images.add(jo_inside.getString("address"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
That Json object 2nd element in the array has space next to name you can solve by 2 ways.
As your backend guys to change that
You solve the problem like this,
Change getString to optString like this
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
String name = jo_inside.optString("name");
if(TextUtils.isEmpty(name)) {
name = jo_inside.optString("name "); // that object have space
}
names.add(name);
images.add(jo_inside.getString("address"));
}
Your Json file contain wrong format JSON.
Remove , from the last array element
{
"name": "cc",
"address": "c"
},
The valid Json should be:
{
"users": [{
"name": "aa",
"address": "a"
},
{
"name": "bb",
"address": "b"
},
{
"name": "cc",
"address": "c"
}
]
}
You have problem in your JSON string only. In second JSON name field has extra space. And also there is , after last JSON },
{
"users": [{
"name":"aa",
"address":"a"
},
{
"name":"bb",
"address":"b"
},
{
"name":"cc",
"address":"c"
}
]
}

How do we pass JSONObject as string in getJSONArray();? [duplicate]

This question already has answers here:
How to iterate over a JSONObject?
(15 answers)
Closed 5 years ago.
I want to fetch multiple JSONArray from an JSONObject
JSONObject jsonObject=new JSONObject(response_view);
for(int x=0; x<jsonObject.length(); x++) {
JSONArray jsonArray = jsonObject.getJSONArray("Here I have to pass");
}
This is my JSON,
{
"Mr. VICKRAM SINGH_269": [{
"status": "P",
"date": "2017-02-05"
}, {
"status": "P",
"date": "2017-02-06"
}],
"Mr. VIVEK KUMAR YADAV_276": [{
"status": "P",
"date": "2017-02-05"
}, {
"status": "P",
"date": "2017-02-06"
}]
}
you can parse Json like below:
try{
JSONObject json = new JSONObject(jsonRespondeString);
Iterator<String> iterator = json.keys();
while (iterator.hasNext()){
String key = iterator.next();
JSONArray jsonArray = json.getJSONArray(key);
for(int i=0;i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String value1 = object.getString("key1");
String value2 = object.getString("key2");
}
}
}
catch (JSONException e){
e.printStackTrace();
}
you can get name and id from key like this:
String str="Mr. VICKRAM SINGH_269";
String array[]= str.split("_");
String name =array[0];
String id =array[1];
JSONArray jsonArray=jsonObject.getJSONArray("Write the name of your array here");
and then loop your jsonArray Object

Parsing json (android) [duplicate]

Before I parse json json array, but this json object. Its It drove me to a standstill. How i can parse json like this:
{ "test1": {
"1": {
"action": "0",
"type": "1",
"id": "1",
},
"2": {
"action": "0",
"type": "1",
"id": "2",
}
},
"test2": {
"1": {
"id": "1",
"name": "one"
},
"2": {
"id": "2",
"name": "two"
},
"5": {
"id": "5",
"name": "three"
}
}}
When you don't have a fixed set of keys, that you know upfront, the only way to parse it is to use keys(). It returns an Iterator with the keys contained in the JSONObject. In your case you could have
JSONObject jsonObject = new JSONObject(...);
Iterator<String> iterator = jsonObject.keys();
while(iterator.hasNext()) {
String currentKey = iterator.next();
JSONObject obj = jsonObject.optJSONObject(key);
if (obj != null) {
Iterator<String> iterator2 = obj.keys();
}
}
iterator will return test1 and test2, while iterator2 will return 1 and 2, for test1 and 1 ,2 , 5 for test2
You can create a JSONObject From string as bellow
JSONObject jsonObject = new JSONObject(YOUR_JSON_STRING);
and to parse the jsonObject
JSONObject test1Json = jsonObject.getJSONObject("test1");
JSONObject oneTest1Json = test1Json.getJSONObject("1");
to get String values
String action = oneTest1Json.getString("action");
String type = oneTest1Json.getString("type");
String id = oneTest1Json.getString("id");
Log.d("Json parse","action -"+action+" type -"+type+" id -"+id);
if need them as JSONArray the you can try
public JSONArray getJsonArray (JSONObject jsonObject){
JSONArray nameJsonArray = jsonObject.names();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < nameJsonArray.length(); i++) {
try {
String key = nameJsonArray.getString(i);
jsonArray.put(jsonObject.getString(key));
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray;
}
in case keys like test1,test2,test3...
JSONObject jsonObject = new JSONObject("{'test1':'Kasun', 'test2':'columbo','test3': '29'}");
JSONArray jsonArray = new JSONArray();
for (int i = 1; i <= jsonObject.names().length(); i++) {
try{
jsonArray.put(jsonObject.getString("test" + i));
}catch (JSONException e){
e.printStackTrace();
}
you can get your JSONArray this way.

Categories

Resources