Sort an Array of JSONObjects in a JSONArray Alphabetically - android

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

Related

How to parse JSONArray in android without key

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.

How to remove one element (other type) list and add adapter ...using Json Url

How to remove one element (other type) list and add adapter ...Using Json Url
And Json Response is
[{"ProdType":"Gas","uId":11000},{"ProdType":"Petrol","uId":11001},{"ProdType":"Diesel","uId":11002},{"ProdType":"other type","uId":11003},{"ProdType":"special items","uId":11006}]
Try this code
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
//Remove the element from arraylist
list.remove(position);
//Recreate JSON Array
JSONArray jsArray = new JSONArray(list);
Edit: Using ArrayList will add "\" to the key and values. So, use
JSONArray itself
JSONArray list = new JSONArray();
JSONArray jsonArray = new JSONArray(jsonstring);
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
//Excluding the item at position
if (i != position)
{
list.put(jsonArray.get(i));
}
}
}
Before preparing list, create a data class
class Response{
private void prodType;
private void uid;
//getters and setters
}
While adding each response object to List verify it its type is other type then ignore it

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

How to create JSONObject and JSON ARRAy from json string in android?

My String contains json
result=[{"USER_ID":83,"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"},{"USER_ID":88,"PROJECT_BY_DETAILS":"Test - over ye mountain blue "}]
How to create JSONOBject and JSONarray from this string
I used this code
JSONObject json =new JSONObject(result);
//Get the element that holds the earthquakes ( JSONArray )
JSONArray earthquakes = json.getJSONArray("");
i got error
Error parsing data org.json.JSONException: Value [{"USER_ID":83,"PRO
If it starts with [ its an array, try with:
JSONArray json =new JSONArray(result);
Difference between JSONObject and JSONArray
use this code for your JsonArray:
try {
JSONArray json = new JSONArray(YOUR_JSON_STRING);
for (int i = 0; i < json.length(); i++) {
JSONObject jsonDATA = json.getJSONObject(i);
String jsonid = jsonDATA.getInt("USER_ID");
String jsondetails = jsonDATA.getString("PROJECT_BY_DETAILS");
}
} catch (JSONException e) {
return null;
}
use Gson for you to do that.
That Json response is an array you know it because of the square brackets [].
Create a mapping object (a java class) with field USER_ID and PROJECT_BY_DETAILS.
public class yourClass(){
public String USER_ID;
public String PROJECT_BY_DETAILS;
}
Create a Type array like so.
final Type typeYourObject = new TypeToken>(){}.getType();
define your list private
List yourList;
Using Gson you will convert that array to a List like so
yourList = gson.fromJson(yourJson, typeYourObject);
with that list later you can do whatever you want. Also with Gson convert it back to JsonArray or create a customs JsonObject.
According to my understanding the JSON object looks like this,
{
"RESULT":[
{
"USER_ID":83,
"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"
},
{
"USER_ID":88,
"PROJECT_BY_DETAILS":"Test - over ye mountain blue "
}
]
}
You are converting this to a String and you wish to re-construct the JSON object. The decode function in the android-side would be this,
void jsonDecode(String jsonResponse)
{
try
{
JSONObject jsonRootObject = new JSONObject(jsonResponse);
JSONArray jData = jsonRootObject.getJSONArray("RESULT");
for(int i = 0; i < jData.length(); ++i)
{
JSONObject jObj = jData.getJSONObject(i);
String userID = jObj.optString("USER_ID");
String projectDetails = jObj.optString("PROJECT_BY_DETAILS");
Toast.makeText(context, userID + " -- " + projectDetails,0).show();
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}

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

Categories

Resources