Java 无法将字符串转换为 JsonArray
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6454889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't Convert string to JsonArray
提问by Nava
How do you convert this String into gson.JsonArray?
你如何将这个字符串转换成 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]]";
This is my Code:
这是我的代码:
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);
}
Is this the way to convert this Collections string to JSonArray?
这是将此集合字符串转换为 JSonArray 的方法吗?
采纳答案by AaronYC
To have a string value inside your JSON array, you must remember to backslash escape your double-quotes in your Java program. See the declaration of s below.
要在 JSON 数组中包含字符串值,您必须记住在 Java 程序中使用反斜杠转义双引号。请参阅下面的 s 声明。
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]]";
Your code in the main() method works fine. Below is just a minor modification of your code in the main() method.
您在 main() 方法中的代码工作正常。下面只是对 main() 方法中的代码进行了小幅修改。
System.out.println("String to Json Array Stmt");
JsonParser parser = new JsonParser();
JsonElement tradeElement = parser.parse(s);
JsonArray trade = tradeElement.getAsJsonArray();
System.out.println(trade);
Lastly, remember to prefix your statement "com.google.gson.*" with the keyword "import", as shown below.
最后,记住在您的语句“com.google.gson.*”前面加上关键字“import”,如下所示。
import com.google.gson.*;
回答by Mike Kwan
I don't see the problem. This code runs fine for me:
我看不出问题。这段代码对我来说运行良好:
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 );
}
}
The only problem maybe is that you failed to properly escape the double quotes in your s string literal.
唯一的问题可能是您未能正确转义 s 字符串文字中的双引号。