I'm trying to parse a string with Gson library but without success. Here is my string:
[["-1.816513","52.5487566"],["-1.8164913","52.548824"]]
the problem in this example is that there are no key-value pairs. I looked at other examples but all of them had key-value pairs and didn't look like my problem.
My solution to parse a list of list of strings.
package stackoverflow.answers;
import java.lang.reflect.Type;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GsonTest {
public static void main(String[] arg) {
Gson gson = new Gson();
String jsonOutput = "[[\"-1.816513\",\"52.5487566\"],[\"-1.8164913\",\"52.548824\"]]";
Type listType = new TypeToken<List<List<String>>>() {}.getType();
List<List<String>> strings = (List<List<String>>) gson.fromJson(jsonOutput, listType);
for(List<String> inner: strings){
for(String s: inner){
System.out.println(s);
}
}
}
}
But since values can be "thinked" also a doubles, you can parse them directly changing type into solution:
package stackoverflow.answers;
import java.lang.reflect.Type;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GsonTest {
public static void main(String[] arg) {
Gson gson = new Gson();
String jsonOutput = "[[\"-1.816513\",\"52.5487566\"],[\"-1.8164913\",\"52.548824\"]]";
Type listType = new TypeToken<List<List<Double>>>() {}.getType();
List<List<Double>> numbers = (List<List<Double>>) gson.fromJson(jsonOutput, listType);
for(List<Double> inner: numbers){
for(Double d: inner){
System.out.println(d);
}
}
}
}
Not important in the context, but for future references: Java 7, Gson 2.2.4
One solution, with raw types:
package com.stackoverflow.so18525283;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.List;
public class App {
private static final String INPUT = "[[\"-1.816513\",\"52.5487566\"],[\"-1.8164913\",\"52.548824\"]]";
public static void main(final String[] args) {
final Gson gson = new GsonBuilder().create();
final List<?> fromJson = gson.fromJson(INPUT, List.class);
if (fromJson != null && fromJson.size() > 0 && fromJson.get(0) instanceof List) {
System.out.println(((List<?>) fromJson.get(0)).get(0)); // this is a String
}
}
}
Another solution is to recreate a valid JSON object, same App
as below but with:
public static void main(String[] args) {
final Gson gson = new GsonBuilder().create();
final Foo fromJson = gson.fromJson("{ data: " + INPUT + "}", Foo.class);
// TODO: check for null
System.out.println(fromJson.data.get(0).get(0)); // this is a Double
}
private static class Foo {
List<List<Double>> data;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.