I'm trying to decode a simple two dimensional array of ints I'm getting from javascript, but can't figure it out.
I've tried to use Gson, but couldn't figure out what is the class of the array:
int[][] newMap;
Gson gson = new Gson();
newMap = gson.fromJson (req.getParameter("map"), ?????);
Update: more info
I'm sending a simple 2D array from javascript. that's pretty much the relevant code:
var mapData = new Array(30);
for ( var i = 0; i < mapData.length; i++ ){
mapData[i] = new Array(30);
}
......
$.post('/create_map', { map : JSON.stringify(mapData) } )
in between i'm populating with integers. i just want to send to a servlet and have a 2D array in java
You can try something like this if you want:-
int[][] dummy = new int[0][0]; // The same type as your "newMap"
int[][] newMap;
Gson gson = new Gson();
newMap = gson.fromJson(req.getParameter("map"), dummy.getClass());
Related
I have a following JSON:
{"data":["str1", "str2", "str3"]}
I want to get a List, i.e. ["str1", "str2", "str3"]
My code is:
JSONObject json = new JSONObject();
List list = new ArrayList();
...
// adding data in json
...
list = (List) json.get("data");
This is not working.
you can get this data as a JsonArray
You can customize a little bit of code like it
public static void main(String[] args) throws ParseException {
String data = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
JSONObject json = new JSONObject(
data);
JSONArray jasonArray = json.getJSONArray("data");
List list = new ArrayList();
int size = jasonArray.length();
int i = 0;
while (i < size) {
list.add(jasonArray.get(i));
i++;
}
System.out.println(list);
}
You wish to parse a JSON string using Java code. It is recommended to use a JSON library for Java. There are several. The below code uses Gson. There are many online examples such as Convert String to JsonObject with Gson. You should also familiarize yourself with the Gson API.
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;
public class JsonList {
public static void main(String[] args) {
String json = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
JsonElement elem = JsonParser.parseString(json);
if (elem.isJsonObject()) {
JsonObject obj = elem.getAsJsonObject();
elem = obj.get("data");
if (elem.isJsonArray()) {
JsonArray arr = elem.getAsJsonArray();
List<String> list = new ArrayList<>();
int count = arr.size();
for (int i = 0; i < count; i++) {
elem = arr.get(i);
if (elem.isJsonPrimitive()) {
String str = elem.getAsString();
list.add(str);
}
}
System.out.println(list);
}
}
}
}
Running the above code gives the following output:
[str1, str2, str3]
There are other ways to convert the JsonArray to a List. The above is not the only way. As I wrote earlier, peruse the API documentation and search the Internet.
Behind the scenes, the JSONArray object stores the json data in an ArrayList<Object>, and it has a method called toList(). There's absolutely no need to loop through the JSONArray in order to set values in the array. The simpler code would look something like this
String data = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
JSONObject json = new JSONObject(data);
List<Object> list = json.getJSONArray("data").toList();
System.out.println(myList);
Note: This will create a list of generic Objects. The currently accepted answer doesn't define a type for the List, which is unsafe. It doesn't enforce type safety, and errors will occur at runtime instead of at compile time.
If you want to convert all of the inner objects to a String, you can do this by upcasting the List to an Object, and then casting it to a List<String>. I don't particularly recommend it, but it can be done like this. List<String> list = (List<String>) (Object) json.getJSONArray("data").toList();.
A better way of casting the value to a specific type would be via a stream to call the Object.toString() method.
List<String> list = json.getJSONArray("data").toList().stream().map(Object::toString).collect(Collectors.toList());
or, if you have a specific type you want to cast it to, you can use
List<MyObject> list = json.getJSONArray("data").toList().stream().map(jsonObject -> (MyObject) jsonObject).collect(Collectors.toList());
Finally, as others have pointed out, there are better libraries for dealing with json. Gson is a great library, however I personally prefer Jackson. They both offer similar resources, but I've found that Jackson's ObjectMapper is more customizable and more widely used.
I am quite new to java and android so please keep that in mind.
I have an Arraylist of an Arraylist of integers. These integers are data from the GPS like Latitude, longtitude, speed at that moment and distance, added to an arraylist in OnLocationChanged and all these arraylists are then added to another arraylist.(sort of like a matrix or table)
example: [[timestamp,lat,long,distance_from_start,speed],[...],...] (all are integers)
I want to convert this Arraylist of arraylists so i can save it on the internal storage of my app for use in other activities ( like statistics of this data) and to upload it to a server. I have searched around quite a bit and found that converting an arraylist to json allows this and also makes it easier to create an SQL file of this data. The conversion of the arraylist to json seems easy enough but i can't find any examples of converting an arraylist of arraylists to json. So i dont know if the arraylists in the arraylist are converted to jsonarrays or whatever or if they will be usable and readable from the json file at all. If this is not possible, are there any other alternative ways of doing this?
Thanks a lot!
Use org.json.JsonArray library.
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
public class Test {
public static void main(String[] args) {
List<List<Integer >> list= new ArrayList<List<Integer>>();
List<Integer> list1=new ArrayList();
list1.add(10);
list1.add(20);
list.add(list1);
List<Integer> list2=new ArrayList();
list2.add(60);
list2.add(70);
list.add(list2);
JSONArray jsonArray= new JSONArray(list);
System.out.println(jsonArray);
}
}
output:
[[10,20],[60,70]]
You can use Gson from Google.
Your main functions are: toJson and fromJson.
From the javadoc:
toJson(Object src)
This method serializes the specified object into its equivalent Json representation.
fromJson(String json, Type typeOfT)
This method deserializes the specified Json into an object of the specified type.
For example:
(Serialization)
Gson gson = new Gson();
gson.toJson(1); ==> prints 1
gson.toJson("abcd"); ==> prints "abcd"
gson.toJson(new Long(10)); ==> prints 10
int[] values = { 1 };
gson.toJson(values); ==> prints [1]
(Deserialization)
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String anotherStr = gson.fromJson("[\"abc\"]", String.class);
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
List of Lists of Integers
List<List<Integer >> list = new ArrayList<List<Integer>>();
List<Integer> list1=new ArrayList();
list1.add(100);
list1.add(200);
list.add(list1);
List<Integer> list2=new ArrayList();
list2.add(700);
list2.add(800);
list.add(list2);
Gson gson = new Gson()
String json = gson.toJson(list);
System.out.println(json);
I need to create a JSON object as it was deserialized from a map, but using a Arraylist<Integer> instead of the list as keys and values. What is the best way to create such a JSON using Gson library?
I could only think of first creating a new HashMap from the ArrayList elements and then convert that it to JSON. Not sure if there is a better way than this, avoiding creation of new map.
If you want to avoid the creation of the map, you can use "low level" Gson objects. This is how you can do it:
public class Q20049678 {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(1);
al.add(2);
al.add(3);
al.add(5);
al.add(8);
JsonObject jo = new JsonObject();
for (Integer i : al) {
jo.add(String.valueOf(i), new JsonPrimitive(i));
}
System.out.println(jo.toString());
}
}
This is the result that I formatted with an external tool.
{
"1":1,
"2":2,
"3":3,
"5":5,
"8":8
}
What is the easiest way to convert a Java ArrayList to Object[][]?
For example:
List<MyClass> myList = new ArrayList<MyClass>();
myList.add(myObj1);
myList.add(myObj2);
Object[][] objArray = myList.... How do I convert?
The reason I'm trying to do this is to use the QueryRunner.batch(String sql, Object[][] params) method of DBUtils.
EDIT:
See here for details:
DBUtils QueryRunner.batch()
EDIT2:
I'll try to give some more information.
public class MyObj
{
int myInt;
String myString;
}
MyObj obj1 = new MyObj(1, "test1");
MyObj obj2 = new MyObj(2, "test2");
List<MyObj> myList = new ArrayList<MyObj>();
myList.add(obj1);
myList.add(obj2);
Object[] onedArray = myList.toArray(); // Now I have a 1d array of my list of objects.
Object[] objArray = myList.get(0); // How do I convert each object instance into an array of Objects?
// Intended result would be something like this:
new Object[][] { { 1, "test1" }, { 2, "test2" } };
EDIT3:
One possible solution is this:
I could add a toObjectArray() method to MyObj class.
Surely there must be a better way?
public Object[] toObjectArray()
{
Object[] result = new Object[2];
result[0] = this.myInt;
result[1] = this.myString;
return result;
}
Thanks.
Arraylist is a single dimensional collection because it uses a single dimensional array inside. You cannot convert a single dimensional array to a two dimensional array.
You may have to add more information in case you want to do conversion of 1D to 2D array.
I'm making a ship defense game.
I have a problem with getting the array of waypoints.
The map contains the JSON format(Using GSON)
{
"waypoints" : {
"ship": {
"first_type": [[0,0],[5,7],[2,8],[4,4],[10,10],[12,0],[0,12],[12,8],[8,8]]
},
"boat": {
"first_type": [[0,0],[5,7],[2,8],[4,4],[10,10],[12,0],[0,12],[12,8],[8,8]]
}
}
}
My code:
jse = new JsonParser().parse(in);
in.close();
map_json = jse.getAsJsonObject();
JsonObject wayPoints = map_json.getAsJsonObject("waypoints").getAsJsonObject("ship");
I wrote this one,but it doesn't work.
JsonArray asJsonArray = wayPoints.getAsJsonObject().getAsJsonArray();
How can I foreach the array of objects?
You can simplify your code and retrieve the first_type array using the following code. Same code should pretty much work for the second_type array as well:
JsonArray types = map_json
.getAsJsonObject("waypoints")
.getAsJsonObject("ship")
.getAsJsonArray("first_type";
for(final JsonElement type : types) {
final JsonArray coords = type.getAsJsonArray():
}
wayPoints is a JSON object. It contains another JSON object called ship. And ship contains a JSON array called first_type. So you should get the first_type array from the ship object, and iterate on this array.