gson 无法将字符串转换为JsonArray

2nbm6dog  于 2022-11-06  发布在  其他
关注(0)|答案(3)|浏览(197)

如何将这个String转换成gson.jsonArray?

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]]";

这是我的代码:

com.google.gson.*;
 public static void main(String[] args)
   {
       //Declared S here
       System.out.println("String to Json Array Stmt");
       JsonParser parser = new JsonParser();
       JsonElement tradeElement = parser.parse(s.toString());
       JsonArray trade = tradeElement.getAsJsonArray();
       System.out.println(trade);
    }

这是将此集合字符串转换为JSonArray的方法吗?

envsm3lx

envsm3lx1#

我看不出有什么问题。这段代码对我来说运行得很好:

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

唯一的问题可能是您未能正确转义s字符串文字中的双引号。

相关问题