How to parse JSONArray in android without key - android

I have a response from the server like this:
[
"test1",
[
"test2",
"test3",
"test4"
]
]
I try to parse this response to JSONObject but when log jsonObject.toString(), It doesn't show anything. So I just parse response with JSONArray and want to show in RecyclerView:
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
DataModel dataModel = new DataModel();
dataModel.setId(i);
dataModel.setWord(jsonArray[i]);
temp.add(dataModel);
}
but I have error on jsonArray[i]. I can from the beginning, Do like this:
JSONArray jsonArray = new JSONArray(response);
response = jsonArray.toString().replaceAll(" []" ", "");
String[] words = response.split(",");
And with a for loop, Added data to RecyclerView. But if a word in response contain {"}, this way remove it.
How pare this json?

You have to check for each element whether it is an array or a String and parse it dynamically.
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
//here check if jsonArray[i] is String or not
//if its an array then do
// JSONArray jsonArray2 = new JSONArray(jsonArray[i]);
}

Though the JSON is valid, it has a weird structure. I am not sure if you can fit this JSON in a consistent data model.
Looks like the first element is a String and the second element is another list. Hence you could do something as follows.
List<String> allElements = new ArrayList<>();
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
try {
// Try to parse it to an array
JSONArray elementArr = new JSONArray(jsonArray[i]);
for (int j = 0; j < elementArr.length(); j++) {
// I hope the nested JSON array is not messed up!!
allElements.add(elementArr[j]);
}
} catch (Exception e) {
// The element is not an array, hence add it to the list directly
allElements.add(jsonArray[i]);
}
}
Finally, allElements should have all the strings that you want.

Related

JSON array and object in Android

Parsing JSON array and object in Android
json:https://api.adjaranet.com/api/v1/movies/
I am trying to parse it with the following Java code in Android but unlimited loading when add
moviejson.getJSONObject("genres").getJSONObject("data").getString("primaryName")
half code is
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for(int i =0;i<jsonArray.length(); i++){
JSONObject moviejson = jsonArray.getJSONObject(i);
//if (moviejson.getJSONObject("plot").getJSONObject("data").getString("language").equals("GEO")){
arrayList.add(new MovieItem(
moviejson.getString("id"),
moviejson.getJSONObject("posters").getJSONObject("data").getString("240"),
moviejson.getString("primaryName"),
moviejson.getString("secondaryName"),
moviejson.getString("year"),
moviejson.getJSONObject("plot").getJSONObject("data").getString("description"),
moviejson.getJSONObject("rating").getJSONObject("imdb").getString("score"),
moviejson.getJSONObject("covers").getJSONObject("data").getString("1920"),
moviejson.getJSONObject("genres").getJSONObject("data").getString("primaryName")
));
//}
loading.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
How solve this problem?
In your json content, data inside genres is an array, not object. That's why when you are trying to parse moviejson.getJSONObject("genres").getJSONObject("data") it throws error.
Try
String genreString = "";
int length = moviejson.getJSONObject("genres").getJSONArray("data").length();
for(int j =0 ; j < length ; j++) {
genreString += moviejson.getJSONObject("genres").getJSONArray("data").getJSONObject(j).getString("primaryName");
}

org.json.JSONException: Find specific string from Json Object

I am working in Android and finding json from internet that looks like this:
JSONObject childObject=me.getJSONObject(pos);
String fisrtkey=childObject.getString("A");
JSONArray jsonArray=childObject.getJSONArray("c");
I want to find C21 that is in the A. See the json coming from request.
Can someone help me?
try {
JSONObject j=new JSONObject(data);
JSONArray c= null;
c = j.getJSONArray("This");
JSONObject item=c.getJSONObject(0);
JSONArray me=item.getJSONArray("me");
for(int pos=0;pos<me.length();pos++)
{
JSONObject childObject=me.getJSONObject(pos);
String fisrtkey=childObject.getString("A");
JSONArray jsonArray=childObject.getJSONArray("c");
}
} catch (JSONException e1) {
e1.printStackTrace();
}
//hope this will help you and also check json is invalid or not ,you missed
// bracket of jsonarray "me".
You have missed THIS json array while parsing. First get that and from that json object and then get ME json array. Something like this
JSONObject j = new JSONObject(data);
JSONArray c = j.getJSONArray("This");
JSONObject j1 = c.getJSONArray(0);
JSONArray d = j.getJSONArray("me");
for(int n = 0; n < c.length(); n++) {
JSONObject item = c.getJSONObject(n);
System.out.println(item.getString("A"));
}
Try this:
JSONObject j = new JSONObject(data);
JSONArray c = j.getJSONArray("me");
for(int n = 0; n < c.length(); n++) {
JSONObject person = (JSONObject) c.get(n );
String id = person.getString("A");
...
}

Sort an Array of JSONObjects in a JSONArray Alphabetically

Hi I'm trying to sort a JSONArray of JSONObjects alphabetically but it seems to add in backslashes as it turns it into one big string. Does anyone know how to do arrange a JSONArray of JSONObjects Alphabetically?
I have tried converting the JSONArray to arraylist but it becomes an JSONArray of Strings that are in alphabetical order rather than JSONObjects
public static JSONArray sortJSONArrayAlphabetically(JSONArray jArray) throws JSONException{
ArrayList<String> arrayForSorting = new ArrayList<String>();
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
//FIND OUT COUNT OF JARRAY
arrayForSorting.add(jArray.get(i).toString());
}
Collections.sort(arrayForSorting);
jArray = new JSONArray(arrayForSorting);
}
return jArray;
}
Maybe something like this?
public static JSONArray sortJSONArrayAlphabetically(JSONArray jArray) throws JSONException
{
if (jArray != null) {
// Sort:
ArrayList<String> arrayForSorting = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
arrayForSorting.add(jArray.get(i).toString());
}
Collections.sort(arrayForSorting);
// Prepare and send result:
JSONArray resultArray = new JSONArray();
for (int i = 0; i < arrayForSorting.length(); i++) {
resultArray.put(new JSONObject(arrayForSorting.get(i)));
}
return resultArray;
}
return null; // Return error.
}
The function's caller can free the JSONArray and JSONObject elements when he no longer needs them.
Also, if you just want to sort a JSONArray, you can look here:
Sort JSON alphabetically
and eventually here:
Simple function to sort an array of objects

getting JSONArray at Index from JSONObject

I have a JSONObject with multiple JSONArrays in it. I have written a for loop to loop through the object but i need to get the JSONArray at the Index position. Does anyone know how to do this?
heres my JSONObject
{"Contacts": //JSONObject
{
"B"://JSONArray..
[
{"ContactName":sdfsdf,"ID":900,"Number":1368349},
{"ContactName":adsdfd,"ID":1900,"Number":136856},
{"ContactName":adglkhdofg,"ID":600,"Number":136845}
],
"C":[
{"ContactName":alkghoi,"ID":900,"Number":1368349},
{"ContactName":wetete,"ID":1900,"Number":136856},
{"ContactName":dfhtfh,"ID":600,"Number":136845}
]
.....//and so on..
}
}
heres my for loop this issue i'm having is that to retrieve a JSONArray from a JSONObject it requires a string but i'm trying to get the Array at object Index in the JSONObject
JSONArray headerStrings = contacts.names();
Log.v("Main", "headerStrings = " + headerStrings);
SeparatedListAdapter adapter = new SeparatedListAdapter(this);
for (int t=0; t<contacts.length(); t++){
adapter.addSection(headerStrings.getString(t), new DocumentArrayAdapter (getActivity(),R.layout.document_cell,contacts.getJSONArray(t););
}
Try this:
for (Iterator it = contacts.keys(); it.hasNext(); ) {
String name = (String)it.next();
JSONArray arr = contacts.optJSONArray(name);
// now add this to your adapter
}
Note, that the order of the elements of a JSONObject is not defined.
Here, You will get matched index.
int matchedIndex =0;
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if( 123 == jsonObject.getInt("Id")){
matchedIndex = i;
//jsonArraySelectedBikes.remove(matchedIndex);
break;
}
}

Problems with getting values from JSON object

I'm trying to get data once user logged in successfully but I never get any of results, what I am doing is next:
// response is my request to server
JSONObject obj = new JSONObject(response);
Log.d("RESPONSE",obj.toString());
so in log I do see values, like:
04-19 11:28:16.729: D/RESPONSE(3162): {"data":[{"loses":3,"username":"benedict","level":1,"strength":15,"experience":null,"gold":10,"password":"benedict","intelligence":5,"agility":10,"wins":5}],"status":true}
but once I try to read username for example like this:
String username = obj.getString("username");
The code above ^ gives me nothing in my string..
Any help how I can retrieve data from JSONObject? Thanks!
That is because the username is present in the data object, which happens to be an JSONArray. Get the data array from the response object, traverse through each JSONObject in the array, and from each object, extract your username.
Something like this:-
JSONObject obj = new JSONObject(response);
JSONArray data = obj.getJSONArray("data");
for(int i=0;i<data.length();i++){
JSONObject eachData = data.getJSONObject(i);
System.out.println("Username= "+ eachData.getString("username"));
}
your field username is in array data. To access into this try :
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("data");
for(int i = 0; i < array.length(); ++i){
JSONObject data = array.getJSONObject(i);
String username = data.getString("username");
}
You need to first get JSONArray which is data :
JSONArray data = null;
data = json.getJSONArray("data");
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
String username = c.getString("username");
}
You can get idea about parsing JSON from HERE
Try this...
try {
JSONObject object = new JSONObject(response);
JSONArray Jarray = object.getJSONArray("data");
for (int i = 0; i < Jarray.length(); i++) {
JSONObject Jasonobject = Jarray.getJSONObject(i);
String loose= Jasonobject.getString("loses");
String username=Jasonobject.getString("username");
.......
........
}
} catch (JSONException e) {
Log.e("log_txt", "Error parsing data " + e.toString());
}

Categories

Resources