Gson解析没有键值对的字符串 [英] Gson parsing string that has no key-value pairs

查看:334
本文介绍了Gson解析没有键值对的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Gson库解析字符串,但是没有成功.这是我的字符串:

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);
      }
    }

  }
}

在上下文中并不重要,但对于将来的参考而言:Java 7,Gson 2.2.4

Not important in the context, but for future references: Java 7, Gson 2.2.4

这篇关于Gson解析没有键值对的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆