Hi I need to read all key, values from nested JSON, where ever there is inner JSON. I need that values ignoring the key.From below JSON i need Key values for nested JSON, like: responseStatus-passed, "statusCode":"200", "retrieveQuoteResponse":null,"quoteGuid":null, etc.ignoring the start key value like: responsePreamble, quoteProductList which has a nested json inside it.
{
"responsePreamble": {
"responseStatus": "Passed",
"statusCode": "200",
"responseMessage": "Records Found"
},
"retrieveQuoteResponse": null,
"totalQuoteProductCount": 2,
"quoteProductList": {
"quoteGuid": null,
"quantity": 180
}
Code:
ObjectReader reader = new ObjectMapper().readerFor(Map.class);
Map<String, Map<String, String>> employeeMap = reader.readValue(jsonObject);
for (Entry<String, Map<String, String>> empMap : employeeMap.entrySet()) {
Map<String, String> addMap = empMap.getValue();
if(addMap!=null) {
for (Entry<String, String> addressSet : addMap.entrySet()) {
System.out.println(addressSet.getKey() + " :: " + addressSet.getValue());
}
}
}
OutPut:
responseStatus :: Passed
statusCode :: 200
responseMessage :: Records Found
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map
at com.im.api.tests.CompareTwoJsons.main(CompareTwoJsons.java:78)
For your specific case, the following code will do the job:
String json = "{\n" +
" \"responsePreamble\":{\n" +
" \"responseStatus\":\"Passed\",\n" +
" \"statusCode\":\"200\",\n" +
" \"responseMessage\":\"Records Found\",\n" +
" \"accountInfo\":{\n" +
" \"id\":\"631b3d5b-62c8-e711-80f3-3863bb343ba0\"\n" +
" },\n" +
" \"account\":\"40114570\",\n" +
" \"contactInfo\":{\n" +
" \"id\":\"1af63ebb-2680-eb11-a812-000d3a4e381d\"\n" +
" },\n" +
" \"contact\":\"Kenny Tokuda\",\n" +
" \"currencyInfo\":{\n" +
" \"id\":\"8c2ef-\",\n" +
" \"symbol\":\"$\"\n" +
" },\n" +
" \"vendorCurrencyInfo\":{\n" +
" \"id\":null\n" +
" }\n" +
" },\n" +
" \"retrieveQuoteResponse\":null,\n" +
" \"totalQuoteProductCount\":2,\n" +
" \"quoteProductList\":{\n" +
" \"quoteGuid\":null,\n" +
" \"quantity\":180\n" +
" }\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(json);
Iterator<String> iterator = jsonNode.fieldNames();
while (iterator.hasNext()) {
String key = iterator.next();
printRec(jsonNode, key);
}
Here is how function printRec looks like:
public static void printRec(JsonNode jsonNode, String key) {
JsonNode node = jsonNode.get(key);
if (node.isObject()) {
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
fields.forEachRemaining(field -> {
printRec(node, field.getKey());
if (!field.getValue().isObject()) {
System.out.println(field.getKey() + " : " + field.getValue());
}
});
}
}
When you run this code you should see the following output:
responseStatus : "Passed"
statusCode : "200"
responseMessage : "Records Found"
id : "631b3d5b-62c8-e711-80f3-3863bb343ba0"
account : "40114570"
id : "1af63ebb-2680-eb11-a812-000d3a4e381d"
contact : "Kenny Tokuda"
id : "8c2ef-"
symbol : "$"
id : null
quoteGuid : null
quantity : 180
Related
I want to convert JSON response to Map what is the best approach to get the desired output using GSON library.
I try this and I'm getting only the ArrayList value.
Map<String, Object> map = gson.fromJson(response, HashMap.class);
ArrayList responseOptions = (ArrayList) map.get("data");
output:
[{language=Java, value=8}, {language=Ruby, value=7}, {language=Python, value=7}]
Sample JSON Response
{
"data":[
{
"language":"Java","value":"8"
},
{
"language":"Ruby","value":"7"
},
{
"language":"Python","value":"6"
}]
}
Desired Output in Map
{Java=8, Ruby=7, Python=6}
Test code
String str = "{\n" +
" \"data\":[\n" +
" {\n" +
" \"language\":\"Java\",\"value\":\"8\"\n" +
" },\n" +
" {\n" +
" \"language\":\"Ruby\",\"value\":\"7\"\n" +
" },\n" +
" {\n" +
" \"language\":\"Python\",\"value\":\"6\"\n" +
" }]\n" +
"}";
Map map = new Gson().fromJson(str, Map.class);
List data = (List) map.get("data");
Map<String, String> result = new HashMap<>();
for (Object o : data) {
Map m = (Map) o;
result.put(m.get("language").toString(), m.get("value").toString());
}
System.out.println(result);
Test result
I'm using rest template in Spring.. I have parsed data to rest template with json following as:
result =
[
{
"sendMessage": {
"to": "84978965123",
"telco": "04",
"type": 1,
"from": "SMS",
"message": "String of message",
"scheduled": "27-07-2021 13:00",
"requestId": "",
"useUnicode": 0,
"ext": "{}"
},
},
{
"sendMessage": {
"to": "84902032618",
"telco": "01",
"type": 1,
"from": "SMS",
"message": "String of message",
"scheduled": "27-07-2021 13:00",
"requestId": "",
"useUnicode": 0,
"ext": "{}"
}
}
]
With result is string of json, i want to insert all data into database, and then my sources of controller:
try {
if(result != null && !result.isEmpty()) {
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> listSendMessage = mapper.readValue(result, new TypeReference<List<Map<String, Object>>>(){});
for(Map<String,Object> listElementIndex : listSendMessage) {
List<Map<String, Object>> data = (List<Map<String, Object>>) listElementIndex.get("mobileNoItems");
for (int i = 0; i < data.size(); i++) {
System.out.println(data.get(i));
data.get(i).get("to");
data.get(i).get("telco");
data.get(i).get("type");
data.get(i).get("from");
data.get(i).get("message");
data.get(i).get("scheduled");
data.get(i).get("requestId");
data.get(i).get("useUnicode");
data.get(i).get("ext");
}
smsService.insertNewScheduleSMS(data);
}
}
else {
logger.debug(SMSConstant.REQUEST_NO_BODY);
}
}
catch(Exception e) {
System.out.println(e.getMessage());
}
When i run and debug it happen an exception is null, and cannot insert string list json into database..
2021-07-28 18:49:53,221 DEBUG [com.myservice.SMSBrandingController] body : {"ext":"{}","useUnicode":"0","scheduled":"28-07-2021 19:00","requestId":"","from":"SMS ","to":"0902032618","type":"1","message":"String of message"}
2021-07-28 18:49:53,221 DEBUG [com.myservice.SMSBrandingController] =======================log result end=================================================
null
(UPDATED:)
Can not deserialize instance of java.util.LinkedHashMap out of VALUE_NUMBER_INT token
at [Source: [{"sendMessage":{"to":"84979123456","telco":"04","type":1,"from":"SMS","message":"String of message","scheduled":"28-07-2021 22:00","requestId":"","useUnicode":0,"ext":"{}"},"msgLength":162,"mtCount":2,"account":"Myaccount","errorCode":"000","errorMessage":"","referentId":"API_CSKH_myaccount_e293c777c0bc4852b6a20dc7d3f507b9"},{"sendMessage":{"to":"84902032618","telco":"01","type":1,"from":"SMS","message":"String of message","scheduled":"28-07-2021 22:00","requestId":"","useUnicode":0,"ext":"{}"},"msgLength":162,"mtCount":2,"account":"myaccount","errorCode":"000","errorMessage":"","referentId":"API_CSKH_myaccount_838ad57022d14fc8b8f01c302858d8da"}]; line: 1, column: 339] (through reference chain: java.util.ArrayList[0]->java.util.LinkedHashMap["msgLength"])
How I can fix the problem ??
The line List<Map<String, Object>> data = (List<Map<String, Object>>) listElementIndex.get("mobileNoItems"); is the problem, its "sendMessage" but not "mobileNoItems"
List<Map<String, Object>> data =
(List<Map<String, Object>>) listElementIndex.get("sendMessage");
prove (Btw I also changed the TypeReference to omit the cast):
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Questions68560156 {
String json = (""
+ "[ "
+ " { "
+ " 'sendMessage': { "
+ " 'to': '84942965123', "
+ " 'telco': '04', "
+ " 'type': 1, "
+ " 'from': 'SMS', "
+ " 'message': 'String of message', "
+ " 'scheduled': '27-07-2021 13:00', "
+ " 'requestId': '', "
+ " 'useUnicode': 0, "
+ " 'ext': '{}' "
+ " }, "
+ " 'msgLength' : 162 "
+ " }, "
+ " { "
+ " 'sendMessage': { "
+ " 'to': '84902032618', "
+ " 'telco': '01', "
+ " 'type': 1, "
+ " 'from': 'SMS', "
+ " 'message': 'String of message', "
+ " 'scheduled': '27-07-2021 13:00', "
+ " 'requestId': '', "
+ " 'useUnicode': 0, "
+ " 'ext': '{}' "
+ " } "
+ " } "
+ "] ").replace('\'', '"');
#Test
public void test() throws JsonMappingException, JsonProcessingException {
method(json);
}
void method(String result) throws JsonMappingException, JsonProcessingException {
if (result != null && !result.isEmpty()) {
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> listSendMessage = mapper.readValue(result,
new TypeReference<List<Map<String, Object>>>() {
});
for (Map<String, Object> listElementIndex : listSendMessage) {
#SuppressWarnings("unchecked")
Map<String, Object> attributes = (Map<String, Object>)listElementIndex.get("sendMessage");
System.out.println(attributes);
//...
}
} else {
// logger.debug(SMSConstant.REQUEST_NO_BODY);
}
}
}
Prints:
{to=84942965123, telco=04, type=1, from=SMS, message=String of message, scheduled=27-07-2021 13:00, requestId=, useUnicode=0, ext={}}
{to=84902032618, telco=01, type=1, from=SMS, message=String of message, scheduled=27-07-2021 13:00, requestId=, useUnicode=0, ext={}}
I have
data= [{
id=1,
employee_name=Tiger Nixon,
employee_salary=320800,
employee_age=61,
profile_image=
},
{
id=2,
employee_name=Garrett Winters,
employee_salary=170750,
employee_age=63,
profile_image=
},
{
id=3,
employee_name=Ashton Cox,
employee_salary=86000,
employee_age=66,
profile_image=
},
{
id=4,
employee_name=Cedric Kelly,
employee_salary=433060,
employee_age=22,
profile_image=
}
]
I have employee class
public class Employee {
private String employee_name;
private String employee_salary;
private String employee_age;
private String id;
private String profile_image;
public String toCsvRow() {
String csvRow = "";
for (String value : Arrays.asList(employee_name,employee_salary,employee_age)) {
String processed = value;
if (value.contains("\"") || value.contains(",")) {
processed = "\"" + value.replaceAll("\"", "\"\"") + "\"";
}
csvRow += "," + processed;
}
return csvRow.substring(1);
}
public String getEmployee_name() {
return employee_name;
}
public String getEmployee_salary() {
return employee_salary;
}
public String getEmployee_age() {
return employee_age;
}
}
I tried for
Map<String, ArrayList<Employee>> map = mapper.readValue(url, Map.class);
ArrayList<Employee> emps = map.get("data");
emps.get(0).toCsvRow()
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.example.model.Employee
Now I cannot call toCSVRow using emps.
Use Gson to parse JSON to ArrayList, for CSV conversion you can use org.json.CDL
See this is working fine
String str = "[{" +
" id=1," +
" employee_name=\"Tiger Nixon\"," +
" employee_salary=320800," +
" employee_age=61," +
" profile_image=\"khkjh\"" +
" }," +
" {" +
" id=2," +
" employee_name=\"Garrett Winters\"," +
" employee_salary=170750," +
" employee_age=63," +
" profile_image=\"\"" +
" }," +
" {" +
" id=3," +
" employee_name=\"Ashton Cox\"," +
" employee_salary=86000," +
" employee_age=66," +
" profile_image=\"\"" +
" }," +
" {" +
" id=4," +
" employee_name=\"Cedric Kelly\"," +
" employee_salary=433060," +
" employee_age=22," +
" profile_image=\"\"" +
" }" +
" ]";
try{
Gson gson = new Gson();
ArrayList<Employee> list = gson.fromJson(str, ArrayList.class);
String csv = CDL.toString(new JSONArray(list));
}catch (Exception e){
e.printStackTrace();
}
Output:
id,employee_name,employee_salary,employee_age,profile_image
1.0,Tiger Nixon,320800.0,61.0,khkjh
2.0,Garrett Winters,170750.0,63.0,
3.0,Ashton Cox,86000.0,66.0,
4.0,Cedric Kelly,433060.0,22.0
I have some dynamic JSON where I won't know the full structure before processing.
However, I do know the JSON may contain certain nested elements of interest.
e. for this sample payload
{
"id": "3334343",
"contractor": {
"ppsNo": "123334"
},
"fullTimeStaff":{
"ppsNo": "343434"
}
}
I would like to find the name of all the outer elements that contain an element named ppsNo.
I have tried using root.findParents("ppsNo") but that gives me the ppsNo elements rather than the outer(parent) elements of contractor and fullTimeStaff that im interested in.
ObjectMapper objectMapper = new ObjectMapper();
String payload = "{\n" +
" \"id\": \"3334343\",\n" +
" \"contractor\": {\n" +
" \"ppsNo\": \"123334\"\n" +
" },\n" +
" \"fullTimeStaff\":{\n" +
" \"ppsNo\": \"123334\"\n" +
" }\n" +
"}";
JsonNode root = objectMapper.readTree(payload);
List<JsonNode> nodes = root.findParents("ppsNo");
The JsonNodes returned are the {"ppsNo":"123334"} elements rather than the outer containing nodes ("contractor" and "fullTimeStaff").
Is there a way to do this? I had looked at using JSON path but i couldn't see an obvious way to get the real parent (containing/outer) element using that as well.
I'm using Jackson in this example but im open to alternatives
There is an option with the JsonPath library that returns the entire matched paths instead of the values. Thus you can do something like:
Configuration conf = Configuration.builder().options(Option.AS_PATH_LIST).build();
List<String> pathList = JsonPath.using(conf).parse(payload).read("$..ppsNo");
/* Returns :
* [
* "$['contractor']['ppsNo']",
* "$['fullTimeStaff']['ppsNo']"
* ]
*/
You just have to parse the result to the correct type, and remove the last element to get the direct parent.
Pattern pattern = Pattern.compile("(?<!\\$\\[)(\\w+)(?!\\])");
pathList = pathList.stream().map(path -> {
Matcher m = pattern.matcher(path.toString());
return m.find() ? m.group(0) : null;
}).collect(Collectors.toList());
System.out.println(pathList); // [contractor, fullTimeStaff]
Here is the link to the official Jayway JsonPath Maven repository.
i didn't put a lot of time to write the code.
the expression you are looking for in Regex is \{\n "ppsNo": "\w+"\n } ( you test it using link https://regex101.com ). what you should do is when you encounter this expression start coming backward and read the first word in " ". i hope it helped you
We can use recursion to search for the target parent nodes with the help of JsonNode.fields method as following example.
public class GetParentByChildName {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String payload = "{ \n"
+ " \"id\": \"3334343\", \n"
+ " \"contractor\": { \n"
+ " \"ppsNo\": \"123334\" \n"
+ " }, \n"
+ " \"arr\": [ \n"
+ " { \n"
+ " \"contractor2\": { \n"
+ " \"ppsNo\": \"123334\" \n"
+ " } \n"
+ " }, \n"
+ " [ \n"
+ " { \n"
+ " \"contractor3\": { \n"
+ " \"ppsNo\": \"123334\" \n"
+ " } \n"
+ " } \n"
+ " ] \n"
+ " ], \n"
+ " \"fullTimeStaff\":{ \n"
+ " \"ppsNo\": \"123334\" \n"
+ " } \n"
+ "} ";
JsonNode root = objectMapper.readTree(payload);
List<String> fieldNames = new ArrayList<String>();
getParentName(root, "ppsNo", fieldNames);
System.out.println(fieldNames);
}
private static void getParentName(JsonNode node, String targetChildName, List<String> fieldNames) {
if (node.getNodeType() == JsonNodeType.ARRAY) {
node.elements().forEachRemaining(x -> getParentName(x, targetChildName, fieldNames));
return;
}
if (node.getNodeType() != JsonNodeType.OBJECT) {
return;
}
node.fields().forEachRemaining(x -> {
Iterator<String> iter = x.getValue().fieldNames();
while (iter.hasNext()) {
String fieldName = iter.next();
if (fieldName.equals(targetChildName)) {
fieldNames.add(x.getKey());
}
}
getParentName(x.getValue(), targetChildName, fieldNames);
});
}
}
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\""
+ " }"
+ " }"
+ " ]"
+ "}";
}