I am able to update the value of jsonObject by using key name , here the method which I am using
private static JSONObject setValue(JSONObject json, String key, String newValue) throws JSONException {
Iterator<?> keys = json.keys();
while (keys.hasNext()) {
String k = (String) keys.next();
if (key.equals(k)) {
json.put(key, newValue);
}
Object value = json.opt(k);
if (value instanceof JSONObject) {
setValue((JSONObject) value, key, newValue);
}
}
return json;
}
But this is not working in case of JSONArray object , I tried surfing , tried some method but not able to get desire output , an sample request payload:
{
"sactions": [
{
"fund": "REAL",
"amount": {
"value": 130.24,
"curr": "RMB"
},
"type": "TD",
"desc": "TD",
"code": "PROMO",
"id": "deaedd69e3-6707-4b27-940a-39c3b64abdc7"
}
]
}
Looking an recursive method to update value for any given key.
This is what I tried , but did not work
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator<?> iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym))) {
js1.put(key, valueNew);
return js1;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
if (js1.optJSONArray(key) != null) {
JSONArray jArray = js1.getJSONArray(key);
for (int i = 0; i < jArray.length(); i++) {
js1 = jArray.getJSONObject(i);
}
break;
}
}
}
return js1;
}
This is how I am using the method (Ceating request body using lombok and jakson)
ObjectMapper mapper = new ObjectMapper();
String.valueOf(setValue(new JSONObject(mapper.writeValueAsString(transferFund())),
field, " "))
Thanks in advance
You can utilize JsonPath jayway to save your time.
For example:
String jsonInput = "{\n" +
" \"sactions\": [\n" +
" {\n" +
" \"fund\": \"REAL\",\n" +
" \"amount\": {\n" +
" \"value\": 130.24,\n" +
" \"curr\": \"RMB\"\n" +
" },\n" +
" \"type\": \"TD\",\n" +
" \"desc\": \"TD\",\n" +
" \"code\": \"PROMO\",\n" +
" \"id\": \"deaedd69e3-6707-4b27-940a-39c3b64abdc7\"\n" +
" }\n" +
" ]\n" +
"}";
String newJson = JsonPath.parse(jsonInput).set("$..id", "test").jsonString();
System.out.println(newJson);
Related
I want to convert the following JSON using JsonObect and JsonArray but not able to do so.
{
"query": {
"bool": {
"must": [
{
"match": {
"customer.partnerName": "Synapse"
}
},
{
"range": {
"customer.billing.chargeAmount": {
"gte": 1,
"lte": 100
}
}
}
],
"filter": [
{
"match": {
"customer.configId": 15
}
}
]
}
}
}
I have tried using JsonObject but not able to achieve the result.
This is just plain copy/paste of your json string into AndroidStudio, it splits the string automatically and adds escape slashes.. it looks horrible but the syntax you wrote is perfectly ok..
String jsonString = " {\n" +
" \"query\": {\n" +
" \"bool\": {\n" +
" \"must\": [\n" +
" {\"match\": \n" +
" { \"customer.partnerName\": \"Synapse\" }},\n" +
"\n" +
" {\n" +
"\"range\" : \n" +
"{\n" +
" \"customer.billing.chargeAmount\" : {\n" +
" \"gte\" : 1,\n" +
" \"lte\" : 100\n" +
" }\n" +
" }}\n" +
" ],\n" +
" \"filter\": [\n" +
" { \"match\": { \"customer.configId\": 15 }}\n" +
" ]\n" +
" }\n" +
" }\n" +
" }";
// HERE BEAUTIFIED
/*jsonString = "{\"query\":{\"bool\":{\"must\":[{\"match\":{\"customer.partnerName\":\"Synapse\"}},{\"range\":{\"customer.billing.chargeAmount\":{\"gte\":1,\"lte\":100}}}],\"filter\":[{\"match\":{\"customer.configId\":15}}]}}}";
*/
try {
JSONObject object = new JSONObject(jsonString);
// NO ERRORS, OBJECT CREATED IN MY CASE
} catch (JSONException e) {
e.printStackTrace();
}
the second option you have is to create the object and inner objects and arrays programmatically.. like this..
try {
JSONObject jsonObject = new JSONObject();
JSONObject query = new JSONObject();
jsonObject.put("query", query);
JSONObject bool = new JSONObject();
query.put("bool", bool);
JSONArray must = new JSONArray();
bool.put("must", must);
JSONObject matchWrap = new JSONObject();
JSONObject match = new JSONObject();
match.put("customer.partnerName", "Synapse");
matchWrap.put("match", match);
must.put(matchWrap);
JSONObject rangeWrap = new JSONObject();
JSONObject range = new JSONObject();
JSONObject customerBillingChargeAmount = new JSONObject();
customerBillingChargeAmount.put("gte", 1);
customerBillingChargeAmount.put("lte", 100);
range.put("customer.billing.chargeAmount", customerBillingChargeAmount);
rangeWrap.put("range", range);
must.put(rangeWrap);
JSONArray filter = new JSONArray();
bool.put("filter", filter);
JSONObject match2Wrap = new JSONObject();
JSONObject match2 = new JSONObject();
match2.put("customer.configId", 15);
match2Wrap.put("match", match2);
filter.put(match2Wrap);
String jsonString2 = jsonObject.toString();
// HERE THE SAME JSON STRING AS YOUR INPUT
} catch (JSONException e) {
e.printStackTrace();
}
This yields the same rasult as your input string when stripped of whitespaces tabs linefeeds etc..
I think what you're looking for is json parsing. This is done in the following way:
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(jsonData); //Insert json string data
//Do other stuff
<script>
var txt = '{"query": {"bool": {"must": [{"match": { "customer.partnerName": "Synapse" }},{"range" : { "customer.billing.chargeAmount" : { "gte" : 1, "lte" : 100 } }}],"filter": [{ "match": { "customer.configId": 15 }}]}}}'
var obj = JSON.parse(txt);
debugger;
document.getElementById("demo").innerHTML = obj.query;
</script>
Hace you tried to Google gson ?
Here is the repo, also you can find relevant implementations online as well.
https://github.com/google/gson
Try this:-
JSONObject jsonObject = new JSONObject(/*Pass your string value here*/ new JSONTokener(result.toString()).nextValue().toString());
//get 'query' as JSONObject
JSONObject jresponseData = new JSONObject(jsonObject.getString("query"));
//since 'bool' is insode 'query'
JSONObject jresponseData_2 =jresponseData.getString("bool");
JSONArray jsonArray = new JSONArray(jresponseData_2.getString("must"));
And you will get the result in JSONArray
So, I would say you should use JsonPath lib to do that.
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
Example of the usage
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
...
public void handle(...) {
...
DocumentContext jsonContext = JsonPath.parse(responseBody);
JSONArray jsonPathPreviousUrl = jsonContext.read("$..previous")
...
This will parse your json qickly, effectivly.
{
"feed": {
"data": [
{
"created_time": "2017-12-12T01:24:21+0000",
"message": "This picture of my grandson with Santa",
"id": ""
},
{
"created_time": "",
"message": "",
"id": ""
},
{
"created_time": "",
"message": "",
"id": ""
}
],
"paging": {
"previous": "https://facebook/v3.2/{your-user-id}/feed?format=json&limit=3&since=1542820440",
"next": "https://facebook/v3.2/{your-user-id}/feed?format=json&limit=3&until=1542583212&"
}
},
"id": "{your-user-id}"
}
Javadoc for json-path
Baeldung article
}
this is the json , I wanted to convert to HashMap
`
ob = "{
"arrival": "RONGO",
"segmentPrices": [
{
"id": "",
"localId": "",
"localCode": "",
"localDesignation": "",
"amounts": [
{
"value": 950,
"currency": "Ksh"
}
]
}
]
} ";
Gson gson = new Gson();
HashMap<String,Object> result = new ObjectMapper().readValue(gson.toJson(ob), HashMap.class);
`
but i can't access to amounts object,
the value of result.get("amounts") is null
somebody can please help me for this ?
Using gson 2.0 here is what you can parse your json as HashMap and access amounts array:
public static void main(String[] args) throws IOException {
Gson gson = new Gson();
HashMap<String, Object> map = gson.fromJson(new FileReader("test.json"), HashMap.class);
ArrayList<Object> prices = (ArrayList<Object>) map.get("segmentPrices");
prices.forEach(p -> {
if (p instanceof LinkedHashMap) {
System.out.println(((LinkedHashMap)p).get("amounts"));
}
});
}
test.json file contains your json.
Output is:
[{value=950.0, currency=Ksh}]
You can access the parameters inside the object in the amount array as below:
public static void main(String[] args) throws IOException {
Gson gson = new Gson();
HashMap<String, Object> map = gson.fromJson(new FileReader("test.json"), HashMap.class);
ArrayList<Object> prices = (ArrayList<Object>) map.get("segmentPrices");
prices.forEach(p -> {
if (p instanceof LinkedHashMap) {
ArrayList<Object> amounts = (ArrayList<Object>) (((LinkedHashMap)p).get("amounts"));
amounts.forEach(amount -> {
System.out.println(((HashMap<String,Object>)amount).get("value"));
});
}
});
}
output is :
950.0
you will need the java-son library, if you need to extract the value of value this is how you can do it.
String ob = "{\n"
+ " \"arrival\": \"RONGO\",\n"
+ " \"segmentPrices\": [\n"
+ " {\n"
+ " \"id\": \"\",\n"
+ " \"localId\": \"\",\n"
+ " \"localCode\": \"\",\n"
+ " \"localDesignation\": \"\",\n"
+ " \"amounts\": [\n"
+ " {\n"
+ " \"value\": 950,\n"
+ " \"currency\": \"Ksh\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " ]\n"
+ " } ";
JSONObject json = new JSONObject(ob.toString());
System.out.println(json.getJSONArray("segmentPrices").getJSONObject(0).getJSONArray("amounts").getJSONObject(0).get("value"));
I have a JSON response and I want to store each element in a string. as I am new to JSON, its difficult to find the solution. please suggest me a solution.
the below is my json response.
{
"responseFlag": 1,
"responseMsg": "Successfully retrieved data",
"responseObj": [{
"assets": {
"asset_since": "",
"asset_type": "",
"comments": "",
"estimated_value": "",
"material_status": "SINGLE",
"ownership_of_assets": "",
"pep": "",
"source_of_income": ""
}
},
{
"assets": {
"asset_since": "",
"asset_type": "",
"comments": "",
"estimated_value": "",
"material_status": "SINGLE",
"ownership_of_assets": "",
"pep": "",
"source_of_income": ""
}
}
]
}
I want to store each object elements in an array.
the code I have tried is below.
package mytry;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Mytry {
public static void main(String[] args) {
// TODO code application logic here
String response="{\n" +
" \"responseFlag\": 1,\n" +
" \"responseMsg\": \"Successfully retrieved data\",\n" +
" \"responseObj\": [\n" +
" {\n" +
" \"assets\": {\n" +
" \"asset_since\": \"\",\n" +
" \"asset_type\": \"\",\n" +
" \"comments\": \"\",\n" +
" \"estimated_value\": \"\",\n" +
" \"material_status\": \"SINGLE\",\n" +
" \"ownership_of_assets\": \"\",\n" +
" \"pep\": \"\",\n" +
" \"source_of_income\": \"\"\n" +
" }},\n" +
" {\n" +
" \"assets\": {\n" +
" \"asset_since\": \"\",\n" +
" \"asset_type\": \"\",\n" +
" \"comments\": \"\",\n" +
" \"estimated_value\": \"\",\n" +
" \"material_status\": \"SINGLE\",\n" +
" \"ownership_of_assets\": \"\",\n" +
" \"pep\": \"\",\n" +
" \"source_of_income\": \"\"\n" +
" }}]}";
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(response);
JSONObject jsonObject = (JSONObject) obj;
//System.out.println(jsonObject.toString());
System.out.println("json size=="+jsonObject.size());
System.out.println("hghgfh"+jsonObject.keySet());
Long sflag = (Long) jsonObject.get("responseFlag");
String msg=(String) jsonObject.get("responseMsg");
String resobj=(String) jsonObject.get("responseObj").toString();
//jsonObject.
System.out.println("sflag=="+sflag);
System.out.println("msg=="+msg);
System.out.println("msg=="+resobj);
// JSONArray msg = (JSONArray) jsonObject.get("responseFlag");
// Iterator<String> iterator = msg.iterator();
// while (iterator.hasNext()) {
// System.out.println(iterator.next());
// }
// for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
// String key = (String) iterator.next();
// System.out.println(jsonObject.get(key));
//}
// String asset = (String) jsonObject.get("assets");
// System.out.println("session token"+asset);
//sflag = (Long) jsonObject.get("responseFlag");
//System.out.println("session sflag"+sflag);
} catch (ParseException ex) {
System.out.println(ex);
}
}
}
the response object is
[{
"assets": {
"comments": "",
"asset_since": "",
"material_status": "SINGLE",
"source_of_income": "",
"ownership_of_assets": "",
"asset_type": "",
"pep": "",
"estimated_value": ""
}
}, {
"assets": {
"comments": "",
"asset_since": "",
"material_status": "SINGLE",
"source_of_income": "",
"ownership_of_assets": "",
"asset_type": "",
"pep": "",
"estimated_value": ""
}
}]
I need each asset values to be stored in an array.
Here is a pseudo code. You can fill the missing parts in this code.
String json = "{"responseFlag":1,"responseMsg":"Successfully retrieved data","responseObj":[{"assets":{"asset_since":"","asset_type":"","comments":"","estimated_value":"","material_status":"SINGLE","ownership_of_assets":"","pep":"","source_of_income":""}},{"assets":{"asset_since":"","asset_type":"","comments":"","estimated_value":"","material_status":"SINGLE","ownership_of_assets":"","pep":"","source_of_income":""}}]}";
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("responseObj");
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject arrayJsonObject = jsonArray.getJSONObject(i);
//insert into your list or array
}
If you are using using json-simple-1.1.1 jar. here is the code below:
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(response);
JSONObject jsonObject = (JSONObject) obj;
//System.out.println(jsonObject.toString());
System.out.println("json size==" + jsonObject.size());
System.out.println("hghgfh" + jsonObject.keySet());
JSONArray jsonArray = (JSONArray)jsonObject.get("responseObj");
for(int i=0; i<jsonArray.size(); i++)
{
JSONObject arrayJsonObject = (JSONObject) jsonArray.get(i);
JSONObject assets = (JSONObject) arrayJsonObject.get("assets");
// read the assets to store
}
}catch (Exception e){
}
I am parsing json file and adding the schema information to a nested hash map.But when I tried to print the nested hashmap it is giving me the same values for all key.Need help on how to store data into a nested hashmap correctly.
My json file :
{
"status":"success",
"tables":[
{
"dbname":"idn",
"tableName":"my_monthly_hits_b",
"schema":"(cm11:chararray)",
"location":"/user/mydb/"
},
{
"dbname":"idn",
"tableName": "my_monthly_match",
"schema":"(city:chararray,match:chararray,cm11:chararray)",
"location":"/user/mydb1"
}
]
}
My code :
public Map<String,Map<String,String>> getDataTypes(String responsePath){
Map<String,Map<String,String>> maped = new HashMap<String,Map<String,String>>();
Map<String,String> colDataTypes = new HashMap<String,String>();
try{
JsonParser parser = new JsonParser();
Object obj = parser.parse(new FileReader(responsePath);
JsonObject jObj = (JsonObject) obj;
JsonArray jArray = (JsonArray) jObj.get("tables");
Iterator<JsonElement> itr = jArray.iterator();
while(itr.hasNext())
{
JsonObject innerObj = (JsonObject) itr.next();
JsonElement shm = innerObj.get("schema");
JsonElement jTableName = innerObj.get("tableName");
String tableName = jTableName.toString();
String ss = shm.toString().replaceAll("\"","").replaceAll("[()]",""):
System.out.println("The required JSON string --->" + ss);
if(ss.contains(","){
String[] str = ss.split(",");
for(String s: str){
String[] ptr = s.split(":");
colDataTypes.put(prt[0],ptr[1]);
}
}
else{
String[] str1 = ss.split(":");
colDataTypes.put(str1[0],str1[1]);
}
maped.put(tabName,colDataTypes);
for(String tab : maped.keySet()){
System.out.println("#####" + "Table Name " + tab + "value" + maped.get(tab));
}
}
}
catch(FileNotFoundException ex)
{
}
return maped;
}
You can use a library like Jackson to manipulate the JSON tree (shown here) or marshal the JSON to an object graph.
package foo;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class Foo {
public static void main(String[] args) throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final JsonNode node = mapper.readTree("{ " +
" \"status\":\"success\"," +
" \"tables\":[ " +
" { " +
" \"dbname\":\"idn\"," +
" \"tableName\":\"my_monthly_hits_b\"," +
" \"schema\":\"(cm11:chararray)\"," +
" \"location\":\"/user/mydb/\"" +
" }," +
" { " +
" \"dbname\":\"idn\"," +
" \"tableName\":\"my_monthly_match\"," +
" \"schema\":\"(city:chararray,match:chararray,cm11:chararray)\"," +
" \"location\":\"/user/mydb1\"" +
" }" +
" ]" +
"}");
final ArrayNode tables = (ArrayNode) node.get("tables");
// Add a new schema
final ObjectNode newSchema = tables.addObject();
newSchema.put("dbname", "foo db name");
newSchema.put("tableName", "foo table name");
newSchema.put("schema", "(foo:chararray,bar:chararray)");
newSchema.put("location", "/foo/bar");
mapper.enable(SerializationFeature.INDENT_OUTPUT);
System.out.println(mapper.writeValueAsString(node));
}
}
The example above will print:
{
"status" : "success",
"tables" : [ {
"dbname" : "idn",
"tableName" : "my_monthly_hits_b",
"schema" : "(cm11:chararray)",
"location" : "/user/mydb/"
}, {
"dbname" : "idn",
"tableName" : "my_monthly_match",
"schema" : "(city:chararray,match:chararray,cm11:chararray)",
"location" : "/user/mydb1"
}, {
"dbname" : "foo db name",
"tableName" : "foo table name",
"schema" : "(foo:chararray,bar:chararray)",
"location" : "/foo/bar"
} ]
}
I am trying to parse a JSON string in java to have the individual value printed separately. But while making the program run I get the following error-
Exception in thread "main" java.lang.RuntimeException: Stub!
at org.json.JSONObject.<init>(JSONObject.java:7)
at ShowActivity.main(ShowActivity.java:29)
My Class looks like-
import org.json.JSONException;
import org.json.JSONObject;
public class ShowActivity {
private final static String jString = "{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " }"
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " }"
+ " ]"
+ "}";
private static JSONObject jObject = null;
public static void main(String[] args) throws JSONException {
jObject = new JSONObject(jString);
JSONObject geoObject = jObject.getJSONObject("geodata");
String geoId = geoObject.getString("id");
System.out.println(geoId);
String name = geoObject.getString("name");
System.out.println(name);
String gender=geoObject.getString("gender");
System.out.println(gender);
String lat=geoObject.getString("latitude");
System.out.println(lat);
String longit =geoObject.getString("longitude");
System.out.println(longit);
}
}
Let me know what is it I am missing, or the reason why I do get that error everytime I run the application. Any comments would be appreciated.
See my comment.
You need to include the full org.json library when running as android.jar only contains stubs to compile against.
In addition, you must remove the two instances of extra } in your JSON data following longitude.
private final static String JSON_DATA =
"{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
Apart from that, geodata is in fact not a JSONObject but a JSONArray.
Here is the fully working and tested corrected code:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ShowActivity {
private final static String JSON_DATA =
"{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
public static void main(final String[] argv) throws JSONException {
final JSONObject obj = new JSONObject(JSON_DATA);
final JSONArray geodata = obj.getJSONArray("geodata");
final int n = geodata.length();
for (int i = 0; i < n; ++i) {
final JSONObject person = geodata.getJSONObject(i);
System.out.println(person.getInt("id"));
System.out.println(person.getString("name"));
System.out.println(person.getString("gender"));
System.out.println(person.getDouble("latitude"));
System.out.println(person.getDouble("longitude"));
}
}
}
Here's the output:
C:\dev\scrap>java -cp json.jar;. ShowActivity
1
Julie Sherman
female
37.33774833333334
-121.88670166666667
2
Johnny Depp
male
37.336453
-121.884985
To convert your JSON string to hashmap you can make use of this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
Use this class :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
credit to this blog
This answer may help someone whose requirements are different.
This is your Json string
{
"pageNumber":20,
"pageTitle":"example page title",
"pageInfo": {
"pageName": "Homepage",
"logo": "https://www.example.com/logo.jpg"
},
"posts": [
{
"post_id": "0123456789",
"actor_id": "1001",
"author_name": "Jane Doe",
"post_title": "How to parse JSON in Java",
"comments": [],
"time_of_post": "1234567890"
}
]
}
and this is how to read it
import org.json.JSONArray;
import org.json.JSONObject;
public class ParseJSON {
static String json = "...";
public static void main(String[] args) {
JSONObject obj = new JSONObject(json);
String pageTitle = obj.getString("pageTitle");
String pageNumber= obj.getInt("pageNumber");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
System.out.println(pageNumber);
System.out.println(pageTitle );
System.out.println(pageName);
JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++) {
String post_id = arr.getJSONObject(i).getString("post_id");
System.out.println(post_id);
}
}
}
Looks like for both of your objects (inside the array), you have an extra closing brace after "Longitude".
Firstly there is an extra } after every array object.
Secondly "geodata" is a JSONArray. So instead of JSONObject geoObject = jObject.getJSONObject("geodata"); you have to get it as JSONArray geoObject = jObject.getJSONArray("geodata");
Once you have the JSONArray you can fetch each entry in the JSONArray using geoObject.get(<index>).
I am using org.codehaus.jettison.json.
Here is the example of one Object, For your case you have to use JSONArray.
public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\",\"salary\":56000}}";
try{
JSONObject emp=(new JSONObject(JSON_STRING)).getJSONObject("employee");
String empname=emp.getString("name");
int empsalary=emp.getInt("salary");
String str="Employee Name:"+empname+"\n"+"Employee Salary:"+empsalary;
textView1.setText(str);
}catch (Exception e) {e.printStackTrace();}
//Do when JSON has problem.
}
I don't have time but tried to give an idea. If you still can't do it, then I will help.
you have an extra "}" in each object,
you may write the json string like this:
public class ShowActivity {
private final static String jString = "{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " }"
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " }"
+ " ]"
+ "}";
}