您将 JSON 转换为 Java 很大程度上取决于您用于执行任务的库。这里的其他答案使用该org.json
库,但大多数极客会对它的使用做出激烈反应,因为它很慢。我所知道的最快的库是 Jackson,但我个人更喜欢 Google-GSON,因为它足够快而且非常易于使用。
查看您的示例字符串,您似乎有一个字符串数组。在 Gson 中,您想将它们视为 a Collection
of a Collection
of String
s。这是示例代码:
import java.lang.reflect.Type;
import java.util.Collection;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Main {
public static void main(String[] args) {
// your sample JSON string, converted to a java string
String json = "[\n [\n \"sn1\",\n \"Liquid_level\",\n \"85\"\n ],\n [\n \"sn2\",\n \"Liquid_level,Temperature\",\n \"95\"\n ],\n [\n \"sn2\",\n \"Liquid_level,Temperature\",\n \"50\"\n ],\n [\n \"sn3\",\n \"Liquid_level\",\n \"85.7\"\n ],\n [\n \"sn4\",\n \"Liquid_level\",\n \"90\"\n ],\n [\n \"sn5\",\n \"Volt_meter\",\n \"4.5\"\n ],\n [\n \"sn6\",\n \"Temperature\",\n \"56\"\n ],\n [\n \"sn8\",\n \"Liquid_level\",\n \"30\"\n ]\n]";
// instantiate a Gson object
Gson gson = new Gson();
// define the type of object you want to use it in Java, which is a collection of a collection of strings
Type collectionType = new TypeToken<Collection<Collection<String>>>(){}.getType();
// happiness starts here
Collection<Collection<String>> stringArrays = gson.fromJson(json, collectionType);
// simply print out everything
for (Collection<String> collection : stringArrays) {
for (String s : collection) {
System.out.print(s + ", ");
}
System.out.println();
}
}
}
和输出:
sn1, Liquid_level, 85,
sn2, Liquid_level,Temperature, 95,
sn2, Liquid_level,Temperature, 50,
sn3, Liquid_level, 85.7,
sn4, Liquid_level, 90,
sn5, Volt_meter, 4.5,
sn6, Temperature, 56,
sn8, Liquid_level, 30,
这取自 Google-GSON 用户指南:https ://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples