Build JSONArray of JSONobjects from a string of JSONObjects? - java

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;
}

Related

Java - How to iterate over a list of hashmap?

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

org.json.JSONException: No value for Name JSON extraction error

I am getting this error when I try to get the value for "Name" out of the following JSON:
{
"edges": [
{
"node": {
"Name": "Sunday River",
"Latitude": 44.4672,
"Longitude": 70.8472
}
},
{
"node": {
"Name": "Sugarloaf Mountain",
"Latitude": 45.0314,
"Longitude": 70.3131
}
}
]
}
This is the snippet of code I am using to try and access these values, but I am just testing getting "Name" for now:
String[] nodes = stringBuilder.toString().split("edges");
nodes[1] = "{" + "\"" + "edges" + nodes[1];
String s = nodes[1].substring(0,nodes[1].length()-3);
Log.d(TAG, s);
JSONObject json = new JSONObject(s);
JSONArray jsonArray = json.getJSONArray("edges");
ArrayList<String> allNames = new ArrayList<String>();
ArrayList<String> allLats = new ArrayList<String>();
ArrayList<String> allLongs = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
JSONObject node = jsonArray.getJSONObject(i);
Log.d(TAG, node.toString(1));
String name = node.getString("Name");
Log.d(TAG, name);
}
My output looks like this:
{"edges":[{"node":{"Name":"Sunday River","Latitude":44.4672,"Longitude":70.8472}},{"node":{"Name":"Sugarloaf Mountain","Latitude":45.0314,"Longitude":70.3131}}]}}
{
"node": {
"Name": "Sunday River",
"Latitude": 44.4672,
"Longitude": 70.8472
}
}
org.json.JSONException: No value for Name
I understand that I could use optString and not get the error, but that will not give me the data stored in each node.
Here is a version that works with your unaltered JSON:
public static void main(String... args)
{
String json = "{\"data\":{\"viewer\":{\"allMountains\":{\"edges\":[{\"node\":{\"Name\":\"Sunday River\",\"Latitude\":44.4672,\"Longitude\":70.8472}},{\"node\":{\"Name\":\"Sugarloaf Mountain\",\"Latitude\":45.0314,\"Longitude\":70.3131}}]}}}}";
JSONObject obj = new JSONObject(json);
JSONObject data = obj.getJSONObject("data");
JSONObject viewer = data.getJSONObject("viewer");
JSONObject allMountains = viewer.getJSONObject("allMountains");
// 'edges' is an array
JSONArray edges = allMountains.getJSONArray("edges");
for (Object edge : edges) {
// each of the elements of the 'edge' array are objects
// with one property named 'node', so we need to extract that
JSONObject node = ((JSONObject) edge).getJSONObject("node");
// then we can access the 'node' object's 'Name' property
System.out.println(node.getString("Name"));
}
}

Android: Dynamically Get JSON Array Key Name From JSON

I have a json link, if we open it I get a following result
{
"Status": "Success",
"All_Details": [{
"Types": "0",
"TotalPoints": "0",
"ExpiringToday": 0
}],
"First": [{
"id": "0",
"ImagePath": "http://first.example.png"
}],
"Second": [{
"id": "2",
"ImagePath": "http://second.example.png"
}],
"Third": [{
"id": "3",
"ImagePath": "http://third.example.png"
}],
}
What I need is, I want to dynamically get all the key names like status, All_details, First etc.
And I also want to get the data inside the All_details and First Array.
I used following method
#Override
public void onResponse(JSONObject response) throws JSONException {
VolleyLog.d(TAG, "Home Central OnResponse: " + response);
String statusStr = response.getString("Status");
Log.d(TAG, "Status: " + statusStr);
if (statusStr.equalsIgnoreCase("Success")) {
Iterator iterator = response.keys();
while (iterator.hasNext()) {
String key = (String)iterator.next();
}
}
}
I get all the key names in get stored in the String key. But I am unable to open get the values inside the JSON array, for eg. I need to get the values inside first and second array using the String(Key). How can I do that.???
First, to get the keynames, you can easily iterate through the JSONObject itself as mentioned here:
Iterator<?> keys = response.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( response.get(key) instanceof JSONObject ) {
System.out.println(key); // do whatever you want with it
}
}
Then, to get the values of the array:
JSONArray arr = response.getJSONArray(key);
JSONObject element;
for(int i = 0; i < arr.length(); i++){
element = arr.getJSONObject(i); // which for example will be Types,TotalPoints,ExpiringToday in the case of the first array(All_Details)
}
If you want to get the JSON array from the response JSONObject you can use the JSONArray class. JSONObject has a method to get a JSONArray: getJSONArray(String). Remember to catch the JSONException when trying this. This exception will be thrown if there is no key for example.
Your code could look like this (only the while loop):
while (iterator.hasNext()) {
String key = (String)iterator.next();
try {
JSONArray array = response.getJSONArray(key);
// do some stuff with the array content
} catch(JSONException e) {
// handle the exception.
}
}
You can get the values from the array with the methods of JSONArray (see the documentation)
Something like this will allow you to iterate on array and individual fields once you have extracted the keys using what you have done. Instead of "Types" use the key variable you will create before this.
JSONArray allDetails = response.getJsonArray("All_Details")
for (int i = 0 ; i < allDetails.length(); i++) {
JSONObject allDetail = allDetails.getJSONObject(i);
allDetails.getString("Types");
}
First of all I want to inform you that it's not a valid JSON. Remove the last Comma (,) to make it valid.
Then you can Iterate like here
JSONArray myKeys = response.names();
Try this one
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
try {
String dynamicKey = (String) keys.next();//Your dynamic key
JSONObject item = jsonObject.getJSONObject(dynamicKey);//Your json object for that dynamic key
} catch (JSONException e) {
e.printStackTrace();
}
}

Parsing Json in Android with out using any external libraries

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!

parse json rest response in java

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);
}

Categories