Here you get JSONObject so change this line:
JSONArray jsonArray = new JSONArray(readlocationFeed);
with following:
JSONObject jsnobject = new JSONObject(readlocationFeed);
and after
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
Answer from kyogs on Stack Overflowjava - Convert string to JSON array - Stack Overflow
java - parse string array from JSON - Stack Overflow
parsing - How to parse this jsonarray to string or array java - Stack Overflow
Java - Parse JSON Array of Strings into String Array - Stack Overflow
Here you get JSONObject so change this line:
JSONArray jsonArray = new JSONArray(readlocationFeed);
with following:
JSONObject jsnobject = new JSONObject(readlocationFeed);
and after
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
Input String
[
{
"userName": "sandeep",
"age": 30
},
{
"userName": "vivan",
"age": 5
}
]
Simple Way to Convert String to JSON
public class Test
{
public static void main(String[] args) throws JSONException
{
String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}] ";
JSONArray jsonArr = new JSONArray(data);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jsonObj = jsonArr.getJSONObject(i);
System.out.println(jsonObj);
}
}
}
Output
{"userName":"sandeep","age":30}
{"userName":"vivan","age":5}
the way to do what I wanted was this:
JSONArray temp = jsonObject.getJSONArray("name");
int length = temp.length();
if (length > 0) {
String [] recipients = new String [length];
for (int i = 0; i < length; i++) {
recipients[i] = temp.getString(i);
}
}
You can try to use xstream with json serializer. Take a look this link
So I ended up getting it to work with these changes! I had never worked with JSON before this project and apparently I had it written wrong for what I was trying to do.
JSONParser jsonParser2 = new JSONParser();
try (FileReader reader = new FileReader("Locations.json")) {
Object obj = jsonParser2.parse(reader);
JSONArray locationsList = (JSONArray) obj;
//Iterate over locations array
locationsList.forEach(emp -> parseJSONLocations((JSONObject) emp, locations, objects));
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException | ParseException e) {
System.out.println(e);
}
and then the method to add it all to a class was changed as such:
private static void parseJSONLocations(JSONObject locations, Locations[] location, Objects[] object) {
JSONObject locationObject = (JSONObject) locations.get("locations");
String desc = (String) locationObject.get("description");
String name = (String) locationObject.get("name");
JSONArray objects = (JSONArray) locationObject.get("objects");
Iterator<String> it = objects.iterator();
List<Objects> objs = new ArrayList<>();
while (it.hasNext()) {
String mStr = it.next();
for (Objects elm : object) {
if (elm.getName().equals(mStr)) {
objs.add(elm);
}
}
}
JSONArray directions = (JSONArray) locationObject.get("directions");
Map<String, String> map = new HashMap<>();
Iterator<JSONObject> it2 = directions.iterator();
while (it2.hasNext()) {
JSONObject value = it2.next();
map.put((String) value.get("direction"), (String) value.get("location"));
}
location[index2] = new Locations(desc, name, objs, map);
index2++;
}
But then I also had to change my JSON code, per jgolebiewski's suggestion:
[
{
"locations": {
"description": "You look around the room and see you are in an empty room with 2 doors to the left and to the right. Knowing not how you got there, you decide to figure out how to escape and get back to your normal life.",
"name": "start",
"objects": [],
"directions": [{
"direction": "right",
"location": "empty room1"
}, {
"direction": "left",
"location": "dungeon"
}]
}
},
{
"locations": {
"description": "Inside this room it looks like some sort of dungeon with a cage in the middle and blood lining the wall and floor.",
"name": "dungeon",
"objects": ["map", "torch"],
"directions": [{
"direction": "up",
"location": "hallway2"
}, {
"direction": "down",
"location": "hallway1"
}, {
"direction": "right",
"location": "start"
}]
}
}
]
Thank you for this tutorial for helping as well: https://howtodoinjava.com/library/json-simple-read-write-json-examples/
I am not sure what library you're using for json mapping, but i can give you some advices, which may help:
- when mapping
objectsproperty try to map it toList<String>instead ofString[] - changing
directionsproperty may help to map it to Map object:
try to change this: "directions": [{"right":"empty room1"}, {"left":"dungeon"}]
to this: "directions": {"right":"empty room1", "left":"dungeon"}
use the following snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
I'll just give a little Jackson example:
First create a data holder which has the fields from JSON string
// imports
// ...
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
@JsonProperty("name")
public String mName;
@JsonProperty("url")
public String mUrl;
}
And parse list of MyDataHolders
String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString,
new TypeReference<ArrayList<MyDataHolder>>() {});
Using list items
String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
You're trying to create a JSONObject based on a string that doesn't represent an object, but an array containing one object.
To get the contained object, try
JSONArray inputArray = new JSONArray(jsonString);
JSONObject jo = inputArray.getJSONObject(0);
I think some of your later work is wrong as well, but perhaps this will get you started.
data appears to be an array of arrays. Perhaps you need to call ja.getJSONArray(i)?
for your example:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
you will have to do something of this effect:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
this returns the array object.
Then iterating will be as follows:
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
//The end...
You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).
Hope this helps.
You can prefer quick-json parser to meet your requirement...
quick-json parser is very straight forward, flexible, very fast and customizable. Try this out
[quick-json parser] (https://code.google.com/p/quick-json/) - quick-json features -
Compliant with JSON specification (RFC4627)
High-Performance JSON parser
Supports Flexible/Configurable parsing approach
Configurable validation of key/value pairs of any JSON Heirarchy
Easy to use # Very Less foot print
Raises developer friendly and easy to trace exceptions
Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered
Validating and Non-Validating parser support
Support for two types of configuration (JSON/XML) for using quick-json validating parser
Require JDK 1.5 # No dependency on external libraries
Support for Json Generation through object serialization
Support for collection type selection during parsing process
For e.g.
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
I finally got it:
ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<SomeClass> someClassList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class));
The other answer is correct, but for completeness, here are other ways:
List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);
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;
}
}
Hi,
I am reading json into a Java program, where I am attempting to process it. I'm having some challenges figuring out how to dig down into the data structure, in order to iterate through some of the deeper lists. I'm attaching below excerpts of the Java, and the toy/test json.
Here is the toy/test json:
{
"objects": [
{
"type": "object-1",
"coordinates": [
[
0,
5
],
[
5,
10
],
[
10,
15
],
[
15,
0
]
]
}
]
}What I WANT to do is grab the list of objects associated with the key "objects", and then iterate through the dictionaries that compose the list, further extracting components (coordinates, say, if the type is what i'm after).
The thing is, I don't know how to do this. The code below is an attempt, but it doesn't work.
Here's the Java excerpt:
JSONObject json;
void setup() {
size(800, 494);
// input json file
String inputJsonFile = "input.json";
String inputJsonFileContentsString = "";
try {
inputJsonFileContentsString = readFileIntoString( inputJsonFile );
}
catch (IOException e) {
e.printStackTrace();
}
//JSON parser object to parse read file
JSONObject inputJsonData = parseJSONObject( inputJsonFileContentsString );
// recover list of objects
JSONArray objects = inputJsonData.getJSONArray( "objects" );
// print json data: iterate over list of objects, retrieving type and coordinates
int arrayLength = objects.size();
for ( int i = 0; i < arrayLength; i++ ) {
// THIS DOESN'T WORK
// I want the next dictionary/hash, but how to retrieve it?
JSONObject objectDataHash = objects[ i ];
}
}Thank you. I normally work with Python, it's been a while since I've done a lot of coding in Java so I'm probably missing something obvious.
It is simple JSON object, not an array. You need to iterate through keys and print data:
JSONObject root = new JSONObject(tokener);
Iterator<?> keys = root.keys();
while(keys.hasNext()){
String key = (String)keys.next();
System.out.println(key + "=" + root.getString(key));
}
Please note that above solution prints keys in a random order, due to usage of HashMap internally. Please refer to this SO question describing this behavior.
Your JSON file does not contain an array - it contains an object.
JSON arrays are enclosed in [] brackets; JSON objects are enclosed in {} brackets.
[1, 2, 3] // array
{ one:1, two:2, three:3 } // object
Your code currently extracts the names from this object, then prints those out:
JSONObject root = new JSONObject(tokener);
JSONArray jsonArray = root.names();
Instead of looping over just the names, you need to use the names (keys) to extract each value from the object:
JSONObject root = new JSONObject(tokener);
for (Iterator<?> keys= root.keys(); keys.hasNext();){
System.out.println(key + "=" + root.get(keys.next()));
}
Note that the entries will not print out in any particular order, because JSON objects are not ordered:
An object is an unordered set of name/value pairs -- http://json.org/
See also the documentation for the JSONObject class.