I converted a map to a Json String using the code below
String msg = new JSONObject(map).toString();
How do I parse the above Json String to get the map back in Android with out using any external libraries?
If you have pairs of String/String you can easily restore it this way:
JSONObject obj = new JSONObject(msg);
Iterator<String> keys = obj.keys();
HashMap<String, String> map = new HashMap<String, String>();
while(keys.hasNext()) {
String key = keys.next();
map.put(key, obj.optString(key));
}
You are asking how to parse but I don't see any JSON to parse in your question.
An example parsing method without any library looks like that:
JSONObject jo = new JSONObject(response);
JSONArray rootArray= jo.getJSONArray("jArray");
int rootArrayLength=rootArray.length();
for(int i=0;i<rootArrayLength;i++){
int id= rootArray.getJSONObject(i).getInt("value");
// do same for others too and create an object
}
// create object and make a list
You can also check from my other answer to compare:
Convert String to JsonArray
You can check my answer here for JSON Parsing:
https://stackoverflow.com/questions/21872643/about-json-parsing-exchange-data-with-rest-services/21872688#21872688
For completeness, please find the details below:
JSONObject is the key class for JSON Parsing. This class represent JSON data in key/value pair where values can be of any type: JSONObjects, JSONArrays, Strings, Booleans, Integers, Longs, Doubles
You create JSONObject as:
JSONObject jObject = new JSONObject(result);
where result is the response you obtain from your HTTPRequest.
Use this jObject to get different types using the specific names:
String:
String jsonString = jObject.getString("NAME");
Array:
JSONArray jsonArray = jObject.getJSONArray("NAME");
Eg. For parsing the places results I used following function, where JSON is something like:
"results" : [
{
"geometry" : {
"location" : {
"lat" : 36.817729,
"lng" : 10.18206
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "35a4f720fff88e2cfb94d64bfd7dbe95a8b4a632",
"name" : "Banque Al-Baraka",
"reference" : "CoQBcwAAAJbocdTKVg8I8CzgDdNtBQQaMsaghRlks-IWYl9eDNmFtftPHMgEfVeek_NHJZ2AN9JbiMda1WvREmoeIHBHsNdz9i7gtBaLM1xB93uhema_oswpqD-eRQ9b3fvTo4MhTOeIa7cRJ70BSEtDMONZqFyjqlGvL-5WsiwmqI1F3Vp_EhArWzyFuNrJdly2cHRBNxUJGhQjlcyHs-U2F0ILpN-ce-PHEesdqA",
"types" : [ "bank", "finance", "establishment" ],
"vicinity" : "88 P9, Tunis"
},
{
"geometry" : {
"location" : {
"lat" : 36.861635,
"lng" : 10.164628
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "da42093835270f902f64bc870154e6787fffbc7b",
"name" : "Agence Ennasr",
"reference" : "CnRwAAAAoh-XuMXghUKtv2UtHQJiRXB0ZugUnAkJIyP-vBd2YzTj5GdwIb5XhUS9x5-uY9_OwyQUdMmUeDHYm4KXHFNvOoj7diOOHAGBu-xCI4svIxcCwQ2w063mc2G3lohiScYMNpbKhwnCaggt0H1iknZY6xIQxDvNwVN0wWkVwO8zf_El5hoUwHgmgFflE31LDLj2_rr0uc1zvZM",
"types" : [ "bank", "finance", "establishment" ],
"vicinity" : "Avenue de Hédi Nouira, Ariana"
},
]
Parsing JSON Array
public ArrayList<HashMap<String,String>> parseResult(JSONObject jsonObject) throws JSONException {
JSONArray jsonArray = jsonObject.getJSONArray(Constants.RESULTS);
ArrayList<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
for (int i = 0; i < jsonArray.length(); i++) {
Object object = jsonArray.get(i);
if (object instanceof JSONObject) {
placesList.add(parsePlaceInfo((JSONObject) object));
}
}
return placesList;
}
Parsing simple JSON Object
private HashMap<String, String> parsePlaceInfo(JSONObject place) throws JSONException {
String name = place.getString(Constants.NAME);
String icon = place.getString(Constants.ICON);
String vicinity = place.getString(Constants.VICINITY);
JSONObject locationObject = place.getJSONObject(Constants.GEOMETRY).getJSONObject(Constants.LOCATION);
String lat = locationObject.getString(Constants.LAT);
String lng = locationObject.getString(Constants.LNG);
HashMap<String, String> placeDetails = new HashMap<String, String>();
placeDetails.put(Constants.NAME, name);
placeDetails.put(Constants.ICON, icon);
placeDetails.put(Constants.VICINITY, vicinity);
placeDetails.put(Constants.LAT, lat);
placeDetails.put(Constants.LNG, lng);
return placeDetails;
}
Please note that this is not a complete code. I am providing you main details. Please let me know if you need any specific details regarding the code. Thanks!
Related
I have a following response from a HTTP call which looks like this...
[{"id": 1, "name" : abc, "above50" : true} , {"id": 2, "name" : "xyc", "above50" : false, "kids" : "yes"} ]
I need to iterate through this list and find if there is a key called kids and if there is the key kids, i need to store the value . How do i do it in java?
First you need to parse the json string - it's a list of objects. If you don't have classes to match those objects, by default they can be represented as Map<String, Object>. Then you need to iterate the list, and for every object in it, you have to iterate the entries in the object. If the key matches, store it.
//parse json string with whatever parser you like
List<Map<String, Object>> list = ...;
//iterate every object in the list
for (Map<String, Object> map : list) {
//iterate every entry in the object
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals("kids")) {
//you can store the key and the value however you want/need
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-------------------------------------------
#Test
public void test04() throws IOException {
final String preString = "[{\"id\": 1, \"name\" : \"abc\", \"above50\" : true} , {\"id\": 2, \"name\" : \"xyc\", \"above50\" : false, \"kids\" : \"yes\"} ]";
final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode arrayNode = objectMapper.readTree(preString);
if (arrayNode.isArray()) {
for (JsonNode it : arrayNode) {
final JsonNode kids = it.get("kids");
if (kids != null) {
//TODO: Storage this value by you want
System.out.println(kids.asText());
}
}
}
}
You can use JSONObject or JSONArray
String message = ""list" : [{"id": 1, "name" : abc, "above50" : true} , {"id": 2, "name" : "xyc", "above50" : false, "kids" : "yes"} ]";
JSONObject jsonObject = new JSONObject(message);
JSONArray array = jsonObject.getJsonArray("list");
//so now inside the jsonArray there is 2 jsonObject
//then you can parse the jsonArray and check if there is
//a jsonObject that have "kids" like jsonObject.get("kids") != null
// or jsonObject.getString("kids") != null
I currently have this JSON:
[
{
"example": "12345678",
"test": "0",
"name": "tom",
"testdata": "",
"testtime": 1531209885613
},
{
"example": "12634346",
"test": "43223452234",
"name": "jerry",
"testdata": "pawenkls",
"testtime": 1531209888196
}
]
I am trying to parse through the array to find a value of "testdata" that matches the value of "testdata" that I have generated, which I am currently doing like so:
JsonArray entries = (JsonArray) new JsonParser().parse(blockchainJson);
JsonElement dataHash = ((JsonObject)entries.get(i)).get("dataHash");
Then I wish to find the value of "example" that is in the same array as the "testdata" with the value "pawenkls".
How do I search for the "example" value that is in the same group as the value of "test data" that I have found?
You need to run through the objects in the array and check the value of the testData field against yours. Then read its example field.
String testData = "pawenkls";
JsonArray entries = (JsonArray) new JsonParser().parse(blockchainJson);
String example = null;
for(JsonElement dataHashElement : entries) {
JsonObject currentObject = dataHashElement.getAsJsonObject();
if(testData.equals(currentObject.get("testdata").getAsString())) {
example = currentObject.get("example").getAsString();
break;
}
}
System.out.println("example: "+example);
This prints out
example: 12634346
Here is a Java 8 version doing the same thing:
String testData = "pawenkls";
JsonObject[] objects = new Gson().fromJson(blockchainJson, JsonObject[].class);
Optional<JsonObject> object = Arrays.stream(objects)
.filter(o -> testData.equals(o.get("testdata").getAsString()))
.findFirst();
String example = null;
if(object.isPresent())
example = object.get().get("example").getAsString();
System.out.println("example: "+example);
I am trying to take a file containing JSON objects and put them into a JSONArray.
After removing the initial characters, the string of JSON objects looks like this:
{ "id" : "ajson1", "parent" : "#", "text" : "Simple root node" },
{ "id" : "ajson2", "parent" : "#", "text" : "Root node 2" },
{ "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" },
{ "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" }
I need to take each object and store it in a JSONArray. This is what I have now:
public JSONArray getJSON(File inputFile) throws IOException, JSONException {
String content = FileUtils.readFileToString(inputFile);
content = content.substring(4, content.length() - 1);
JSONObject jsonObject = new JSONObject(content);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
return jsonArray;
}
The correct values are not being stored in the JSONArray. How should I proceed?
Why not simply:
public JSONArray getJSON(File inputFile) throws IOException, JSONException {
String content = FileUtils.readFileToString(inputFile);
content = content.substring(4, content.length() - 1);
JSONArray jsonArray = new JSONArray("[" + content + "]");
return jsonArray;
}
I am trying to parse json output from neo4j in java as:
Object obj = parser.parse(new FileReader("D:\\neo4j.json"));
JSONArray json = (JSONArray) obj;
System.out.println(json.size());
for (int i = 0; i < json.size(); i++) {
JSONObject jsonObject = (JSONObject) json.get(i);
String data = (String);
jsonObject.get("outgoing_relationships");
String name = (String) jsonObject.get("name");
System.out.println(data);
System.out.println(name);
}
Can somebody help me to get values inside "data" element:
I have json output from neo4j as follows:
[{
"outgoing_relationships": "http://host1.in:7474/db/data/node/133/relationships/out",
"data": {
"MOTHERS_NAME": "PARVEEN BAGEM",
"MOBILE_NO": "9211573758",
"GENDER": "M",
"name": "MOHD",
"TEL_NO": "0120-",
"PINCODE": "110001"
},
"traverse": "http://host1.in:7474/db/data/node/133/traverse/{returnType}",
"all_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/all/{-list|&|types}",
"property": "http://host1.in:7474/db/data/node/133/properties/{key}",
"self": "http://host1.in:7474/db/data/node/133",
"properties": "http://lhost1.in:7474/db/data/node/133/properties",
"outgoing_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/out/{-list|&|types}",
"incoming_relationships": "http://host1.in:7474/db/data/node/133/relationships/in",
"extensions": {
},
"create_relationship": "http://host1.in:7474/db/data/node/133/relationships",
"paged_traverse": "http://host1.in:7474/db/data/node/133/paged/traverse/{returnType}{?pageSize,leaseTime}",
"all_relationships": "http://host1.in:7474/db/data/node/133/relationships/all",
"incoming_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/in/{-list|&|types}"
}]
Regards,
Jayendra
You can try following way. Inside the for loop get the data node as JSONObject. From that data node you can extract every property. I just extracted mother name from data.
JSONObject data = (JSONObject) jsonObject.get("data");
final String motherName = (String) data.get("MOTHERS_NAME");
What library are you using to parse JSON ? I'd recommend that you use Jackson
For eg: To get the data you read from the file in a Map, you can write a method like this.
#SuppressWarnings("rawtypes")
public static Map toMap(Object object) throws JsonProcessingException{ ObjectMapper mapper = new ObjectMapper();
return mapper.convertValue(object, Map.class);
}
I have an json feed from bbc in this format
{
"name": "ticker",
"entries": [
{
"headline": "text",
"prompt": "LATEST",
"isBreaking": "false",
"mediaType": "Standard",
"url": ""
},
{
"headline": "text",
"prompt": "LATEST",
"isBreaking": "false",
"mediaType": "Standard",
"url": ""
},
etc...........
My code is as follows:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http:/......");
try{
JSONArray item = json.getJSONArray("entries");
for (int i = 0; i<item.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = item.getJSONObject(i);
JSONObject title = e.JSONObject("headline");
map.put("title", "Title:" + e.getString("headline");
}
}
It gives me the error "java.lang.String cannot be converted to JSONObject"
I also tried leaving out JSONObject title = e.JSONObject("headline"); and it gives me a path error (note
You want e.getString("headline"), not e.JSONObject
use
JSONObject e = item.getJSONObject(i);
map.put("title", "Title:" + e.getString("headline");
instead of
JSONObject e = item.getJSONObject(i);
JSONObject title = e.JSONObject("headline");
map.put("title", "Title:" + e.getString("headline");
becuase e json object not contain any other json object it only contains keys and corresponding values