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}
Videos
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.
Use Gson library, which convert Java object to Json String
String[] sentences=new String[3];
sentences[0]="Hi";
sentences[1]="Hello";
sentences[2]="How r u?";
Gson gson=new GsonBuilder().create();
String jsonArray=gson.toJson(sentences);
//["Hi","Hello","How r u?"]
out.write(jsonArray);
out.flush();
out.close();
The easiest solution is a loop:
StringBuilder sb = new StringBuilder("[");
for(int i = 0; i < array.length; i++) {
sb.append(array[i]);
if(i < array.length-1) {
sb.append(",");
}
}
out.write(sb.append("]").toString());
But this has the problem of producing potentially invalid JSON (unescaped). Hence:
The best solution, however, would be to use a proper JSON/Java binding library such as Jackson, Gson, etc.
If you want or need to work with a Java array then you can always use the java.util.Arrays utility classes' static asList() method to convert your array to a List.
Something along those lines should work.
String mStringArray[] = { "String1", "String2" };
JSONArray mJSONArray = new JSONArray(Arrays.asList(mStringArray));
Beware that code is written offhand so consider it pseudo-code.
ArrayList<String> list = new ArrayList<String>();
list.add("blah");
list.add("bleh");
JSONArray jsArray = new JSONArray(list);
This is only an example using a string 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.
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)
JSONParser parser = new JSONParser();
JSONArray array = (JSONArray)parser.parse("[{\"user_id\": 1}]");
System.out.println(((JSONObject)array.get(0)).get("user_id"));
You need to cast to a JSONArray as that is what the string contains.
For your task you could use code as bellow:
String t = "[{\"user_id\": \"someValue\"}]";
JSONParser parser = new JSONParser();
JSONArray obj = (JSONArray) parser.parse(t);
System.out.println(obj.get(0));
And result would be JSONObject.
If you're talking about using the JSON in java library, then since your input string is a JSON object, not a JSON array, you should first load it using JSONObject:
String response=getResponseFromServer();
JSONObject jsonObject = new JSONObject(response);
After that, you can use toJSONArray() to convert a JSONObject to JSONArray given an array of key strings:
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
If you do a search right here on StackOverflow for Java String to JSONArray, you should get this answer: Converting from JSONArray to String then back again
JSONArray jArray;
String s = jArray.toString(); // basically what you have ;)
JSONArray newJArray = new JSONArray(s);
There are actually two libraries containing the similar JSONArray class which makes it confusing somehow:
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
and
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
The org.json library has a JSONArray class which has a constructor accepting a String that can be parsed to a JSONArray. This is working when you have some simple form of Json array string like this:
["One", "two"]
So you can parse it simply like this to achieve the JSONArray:
import org.json.JSONArray;
public class Test {
public static void main(String[] args) {
String val = "[\"One\", \"Two\"]";
JSONArray jsonArr = new JSONArray(val);
for (int i = 0; i < jsonArr.length(); i++) {
System.out.println( jsonArr.getString( i ) );
}
}
}
But this doesn't work simply for more complex Json strings similar to yours which is containing Json objects with multiple properties.
In this case you may find the other library more helpful. It has a JSONParser class that can parse complex Json objects within the strings:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JSONArrayTest {
public static void main(String[] args) throws ParseException {
String val = "[{\"name\":\"mobilenumber\",\"value\":\"9010000000\"},{\"name\":\"amount\",\"value\":\"200\"},{\"name\":\"ccffee\",\"value\":\"0\"},{\"name\":\"totalfee\",\"value\":\"200\"}]";
JSONArray jsonArr = (JSONArray) new JSONParser().parse( val );
for (int i = 0; i < jsonArr.size(); i++) {
JSONObject jsonObj = (JSONObject) jsonArr.get( i );
System.out.println( jsonObj );
}
}
}
Hope this would be helpful.
You could try
JSONParser parse = new JSONParser();
org.json.simple.JSONObject jobj=(org.json.simple.JSONObject)parse.parse(your String);
Iterator obj = jobj.keys();
JSONArray jsonArray = new JSONArray();
while (obj.hasNext()){
String key = (String) obj.next();
jsonArray.put(obj.get(key));
}