How to Loop Through Dynamic JSON String Recursively in Android

Unable to Loop through dynamic json string recursively in android

Did you debug and check where exactly does it break?

Use a for each loop where you can instead of for(;;)

http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

How does the Java 'for each' loop work?

Also, If you have a complicated json, you may be better off using Gson to map data and your model classes. Eg.:

    Gson gson = new Gson();
ModelClass modelClass= new ModelClass();
modelClass= gson.fromJson(responseContent,ModelClass.class);
//where responseContent is your jsonString
Log.i("Web service response", ""+modelClass.toString());

https://code.google.com/p/google-gson/

For Naming discrepancies(according to the variables in webservice), can use annotations like
@SerializedName. (So no need to use Serializable)

How do i dynamically iterate through a nested JSON and update all the values that are floating type

If the objective is only to find floating point results and round or truncate them, you could turn your JSON into a String and then create an InputStream based on that String to read it into a Scanner object.

String jsonString = obj.toString();
InputStream stream = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8));
Scanner myScanner = new Scanner(stream);

After that you can find the float types using scanner.nextFloat()

You can use the exact output of that value to do a find and replace in your original string.

if (scanner.hasNextFloat()) {
float myFloat = scanner.nextFloat();
String myStringFloat = Float.toString(myFloat);
//Do stuff to your float here.
jsonString.replace(myStringFloat, newFloatValue);
}
return jsonString.JSONFunctionToTurnThisBackIntoAnObject();

Build an arraylist of specific object looping recursive function on json object

I think it can be something like this:

class Question {
val questions = listOf<Question>()
}

fun extractQuestions(questionList: List<Question>): List<Question> =
questionList.flatMap { listOf(it) + extractQuestions(it.questions) }

How to parse following json response in android app

try using something like:

jsonResultStr = jsonResultStr.replace( "\\", "" ).replaceAll( "\"\\[", "[" ).replaceAll( "\\]\"", "]" );
JSONObject jObject = new JSONObject(jsonResultStr);
JSONArray jArray = jObject.optJSONArray("data");

JSON Array Splitter in Android

Yes you can do that using

JsonArray productarray = jsonobj.getjsonarray("Productcategory");

now get count

productarray.getCount();

and according to pagenumber click
getdata array
if 1 is clicked
then from 0 to 5 and 1 then 5 to 10
and if you want number of page then

number_of_page = productarray.getCount()/5;

Return a value present from recursive function in Java

There are two errors in your code.

  1. I notice that you recursively call the function getValueFromKey. That will never work if you don't assign the variable foundKey with the return value of the recursive invocation.

    So, just change each recursive calls in this:

    foundKey = getValueFromKey(..., key);

  2. In addition, the last statement return 1 is wrong, because it will override any possible value returned by the subsequent recursive invocation. So, in replacement, you have to return always the foundKey variable.

I slightly changed your code and tested it with your sample file and it works fine. Differently than yours, I also wrapped the BufferedReader with try-with-resouce block, which I always prefer to simple try-catch, because it garantees that it closes the stream for you, even in case of exceptions.

Here is the code:

import java.io.BufferedReader;
import java.io.FileReader;

import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.XML;

public class Test {

static String line = "", str = "";

public static void main(String[] args) throws Exception {

String filepath = "C:\\Users\\marco\\Downloads\\sample.xml";

try ( BufferedReader br = new BufferedReader(new FileReader(filepath)); ) {
while ((line = br.readLine()) != null) {
str += line;
}
}

JSONObject jsondata = XML.toJSONObject(str);

System.out.println("From main: " + getValueFromKey(jsondata, "routing_bic"));
}

private static Integer getValueFromKey(JSONObject json, String key) {
boolean exists = json.has(key);
Iterator<?> keys;
String nextKeys;
Integer foundKey = 0;

if(!exists) {
keys = json.keys();
while (keys.hasNext()) {
// Store next Key in nextKeys
nextKeys = (String)keys.next();

try {
// Check if the given Key is a JSON Object
if(json.get(nextKeys) instanceof JSONObject) {
// If Key does not exist
if(!exists) {
// Recursive function call
foundKey = getValueFromKey(json.getJSONObject(nextKeys), key);
}
} else if (json.get(nextKeys) instanceof JSONArray) {
JSONArray jsonArray = json.getJSONArray(nextKeys);
for(int i = 0; i < jsonArray.length(); i++) {
String jsonArrayString = jsonArray.get(i).toString();
JSONObject innerJsonObject = new JSONObject(jsonArrayString);

// Recursive function call
if(!exists) {
foundKey = getValueFromKey(innerJsonObject.getJSONObject(nextKeys), key);
}
}
}
} catch (Exception e) {
System.out.println(e);
}
}
} else {
// If key exists, print value
foundKey += parseObject(json, key);
System.out.println("From loop: " + foundKey);
}
// System.out.println("Found Key = " + foundKey);
return foundKey; // Return 1 when key not found
}

private static Integer parseObject(JSONObject json, String key) {
System.out.println("From parseObject = " + json.get(key));
return (Integer) json.get(key);
}

}

And here is the output:

From parseObject = 103
From loop: 103
From main: 103


Related Topics



Leave a reply



Submit