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 OverflowHere 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}
Take a look at this tutorial. Also you can parse above json like :
JSONArray arr = new JSONArray(yourJSONresponse);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("name"));
}
Simplest and correct code is:
public static String[] toStringArray(JSONArray array) {
if(array==null)
return new String[0];
String[] arr=new String[array.length()];
for(int i=0; i<arr.length; i++) {
arr[i]=array.optString(i);
}
return arr;
}
Using List<String> is not a good idea, as you know the length of the array.
Observe that it uses arr.length in for condition to avoid calling a method, i.e. array.length(), on each loop.
The problem is not the JSONArray.toString(), as @Selvin mentioned.
From JSONArray source:
/**
* Encodes this array as a compact JSON string, such as:
* <pre>[94043,90210]</pre>
*/
@Override public String toString() {
try {
JSONStringer stringer = new JSONStringer();
writeTo(stringer);
return stringer.toString();
} catch (JSONException e) {
return null;
}
}
/**
* Encodes this array as a human readable JSON string for debugging, such
* as:
* <pre>
* [
* 94043,
* 90210
* ]</pre>
*
* @param indentSpaces the number of spaces to indent for each level of
* nesting.
*/
public String toString(int indentSpaces) throws JSONException {
JSONStringer stringer = new JSONStringer(indentSpaces);
writeTo(stringer);
return stringer.toString();
}
The problem is that you need to convert your ChecklistAnswer to JSON object first for your JSONArray to work properly.
Again from Javadoc:
/**
* A dense indexed sequence of values. Values may be any mix of
* {@link JSONObject JSONObjects}, other {@link JSONArray JSONArrays}, Strings,
* Booleans, Integers, Longs, Doubles, {@code null} or {@link JSONObject#NULL}.
* Values may not be {@link Double#isNaN() NaNs}, {@link Double#isInfinite()
* infinities}, or of any type not listed here.
...
In my ChecklistAnwer class i added:
public JSONObject toJsonObject(){
JSONObject json = new JSONObject();
try {
json.put("questionId", questionId);
json.put("checklistId", checklistId);
json.put("answer", answer);
json.put("remark", remark);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
and in my other class:
JSONArray answers = new JSONArray();
ChecklistAnswer answer = new ChecklistAnswer(questions.get(id).id, 2, cb.isChecked(), text.getText().toString());
answers.put(answer.toJsonObject());
if i filled the array:
String js = answers.toString(1);
and that returns:
[
{
"answer": true,
"questionId": 1,
"remark": "",
"checklistId": 2
},
{
"answer": false,
"questionId": 4,
"remark": "teesxfgtfghyfj",
"checklistId": 2
},
{
"answer": true,
"questionId": 4,
"remark": "",
"checklistId": 2
},
{
"answer": true,
"questionId": 4,
"remark": "",
"checklistId": 2
},
{
"answer": true,
"questionId": 4,
"remark": "",
"checklistId": 2
},
{
"answer": true,
"questionId": 4,
"remark": "",
"checklistId": 2
},
{
"answer": true,
"questionId": 4,
"remark": "",
"checklistId": 2
}
]
thanks to @Selvin
Something like this:
ArrayList<String> jsonStringToArray(String jsonString) throws JSONException {
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
stringArray.add(jsonArray.getString(i));
}
return stringArray;
}
You could try something like:
new JSONArray(jsonString)
or if it is a property:
jsonObject.getJSONArray(propertyName)
// you should probably mention what json library you use in your question
String[] cities = new String[cities.length()];
for (int i = 0; i<cities.length(); i++) {
cities[i] = cities.getJsonObject(i).getString("name");
}
cities is an array of JSONObjects. iterate through that array of JSONObjects, and get the "name" attribute from each. See @pb2q's answer where the code has been conveniently written for you.
Use gson. It's got a much friendlier API than org.json.
Collections Examples (from the User Guide):
Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);
//(Serialization)
String json = gson.toJson(ints); ==> json is [1,2,3,4,5]
//(Deserialization)
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);
//ints2 is same as ints
You are right! Even @Sean Patrick Floyd's answer is too much boilterplate to covert a JSON array to string[] or any other type of array class. Rather here is what I find to be elegant:
JsonArray jsonArray = input.getAsJsonArray("key");
Gson gson = new Gson();
String[] output = gson.fromJson(jsonArray , String[].class)
NOTE 1: JsonArray must be an array of strings, for the above example, without any property names. Eg:
{key:["Apple","Orange","Mango","Papaya","Guava"]}
Note 2: JsonObject class used above is from com.google.gson library and not the JSONObject class from org.json library.
Look like you want to store name and location in an array, if yes then
for(int i=0; i < jLocation.length(); i++){
arr[0] = jLocation.getJSONObject(i).getString("name");
arr[1] = jLocation.getJSONObject(i).getString("location");
}
Note - This code assume that you only have one name and location. However I sugegst you to do something like below:
Create a Location class, e.g. below
public class Location {
private String name;
private String location;
public Location(String name, String location) {
this.name = name;
this.location = location;
}
public String getName() {
return name;
}
public String getLocation() {
return location;
}
}
Then use it like below:
public static void main(String[] args) {
List<Location> locations = new ArrayList<Location>();
for(int i=0; i < jLocation.length(); i++){
String name = jLocation.getJSONObject(i).getString("name");
String location = jLocation.getJSONObject(i).getString("location");
locations.add(new Location(name, location));
}
}
Try this
//First initiate string
String value1;
String value2;
//Read json
for(int i-0;i < jLocation.length();i++){
value1 = jLocation.getJSONObject(i).getString("name");
value2 = jLocation.getJSONObject(i).getString("location");
}
//Create Stting array
String[ ] arr = {value1,value2};
It will use to add only one value to array.
I prefer ArrayList. Then you can add all the data to ArrayList
To have a string value inside your JSON array, you must remember to backslash escape your double-quotes in your Java program. See the declaration of s below.
String s = "[[\"110917 \", 3.0099999999999998, -0.72999999999999998, 2.8500000000000001, 2.96, 685.0, 38603.0], [\"110917 \", 2.71, 0.20999999999999999, 2.8199999999999998, 2.8999999999999999, 2987.0, 33762.0]]";
Your code in the main() method works fine. Below is just a minor modification of your code in the main() method.
System.out.println("String to Json Array Stmt");
JsonParser parser = new JsonParser();
JsonElement tradeElement = parser.parse(s);
JsonArray trade = tradeElement.getAsJsonArray();
System.out.println(trade);
Lastly, remember to prefix your statement "com.google.gson.*" with the keyword "import", as shown below.
import com.google.gson.*;
I don't see the problem. This code runs fine for me:
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class GsonExample {
public static void main(String[] args) {
String s= "[[\"110917\", 3.0099999999999998, -0.72999999999999998," +
"2.8500000000000001, 2.96, 685.0, 38603.0], [\"110917\", 2.71," +
"0.20999999999999999, 2.8199999999999998, 2.8999999999999999," +
"2987.0, 33762.0]]";
JsonParser parser = new JsonParser();
JsonElement elem = parser.parse( s );
JsonArray elemArr = elem.getAsJsonArray();
System.out.println( elemArr );
}
}
The only problem maybe is that you failed to properly escape the double quotes in your s string literal.
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"}
For anyone else who might need this:
String jsonString = "[\"string1\",\"string2\",\"string3\"]";
ObjectMapper mapper = new ObjectMapper();
List<String> strings = mapper.readValue(jsonString, List.class);
As ryzhman said, you are able to cast it to a List, but only of the object (JSONArray in ryzhman's case) extends the ArrayList class. You don't need an entire method for this. You can simply:
List<String> listOfStrings = new JSONArray(data);
Or if you are using IBM's JSONArray (com.ibm.json.java.JSONArray):
List<String> listOfStrings = (JSONArray) jsonObject.get("key");
Using a stream you could convert it like so:
String s = "[\"A\",\"B\",\"C\",\"D\",\"E\"]";
String[] arr = Arrays.stream(s.substring(1, s.length()-1).split(","))
.map(e -> e.replaceAll("\"", ""))
.toArray(String[]::new);
You could also use a JSON library (which might be the prefered way). For example using Jackson:
String s = "[\"A\",\"B\",\"C\",\"D\",\"E\"]";
ObjectMapper mapper = new ObjectMapper();
String[] arr = mapper.readValue(s, String[].class);
ArrayList<String> jsonStringToArray(String jsonString) throws JSONException {
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
stringArray.add(jsonArray.getString(i));
}
return stringArray;
}