How to parse a dynamic JSON key in a Nested JSON result?
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
Roughly the code will look like:
// searchResult refers to the current element in the array "search_result" but whats searchResult?
JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
// do something here with the value...
}
Another possibility is to use Gson (Note, I use lombok here to generates getters/setters, toString, etc):
package so7304002;
import java.util.List;
import java.util.Map;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class JsonDemo {
@Data
private static class MyMap {
private int count;
@SerializedName("more_description")
private String moreDescription;
private int seq;
}
@Data
private static class Product {
private String product;
private int id;
@SerializedName("question_mark")
private Map<String, MyMap> questionMark;
}
@Data
private static class MyObject {
private String status;
@SerializedName("search_result")
private List<Product> searchResult;
}
private static final String INPUT = ""; // your JSON
public static void main(final String[] arg) {
final MyObject fromJson = new Gson().fromJson(INPUT,
new TypeToken<MyObject>(){}.getType());
final List<Product> searchResult = fromJson.getSearchResult();
for (final Product p : searchResult) {
System.out.println("product: " + p.getProduct()
+ "\n" + p.getQuestionMark()+ "\n");
}
}
}
Output:
product: abc
{141=JsonDemo.MyMap(count=141, moreDescription=this is abc, seq=2),
8911=JsonDemo.MyMap(count=8911, moreDescription=null, seq=1)}
product: XYZ
{379=JsonDemo.MyMap(count=379, moreDescription=null, seq=5),
845=JsonDemo.MyMap(count=845, moreDescription=null, seq=6),
12383=JsonDemo.MyMap(count=12383, moreDescription=null, seq=4),
257258=JsonDemo.MyMap(count=257258, moreDescription=null, seq=1)}