Gson parsing string that does not have a key-value pair

advertisements

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