你的JSON转换为Java的主要取决于您正在使用哪个库来执行任务。这里的其他答案使用org.json
库,但是大多数极客会因其使用情况而发生剧烈反应,因为它非常缓慢。我知道的速度最快的图书馆是杰克逊,但我个人更喜欢Google-GSON,因为它足够快,但仍然非常易于使用。
看着你的示例字符串,你似乎有一个字符串数组的数组。在Gson,你想把它们看作Collection
的Collection
的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,
这是从谷歌,GSON用户指南采取:https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples
你要提供方法的更多信息。你的服务器上运行什么软件?你对应用程序有控制吗?如果是这样,你可以控制它通过输出的方式发送给客户端,并从那里... – Ben
我得到一个使用PHP脚本的JSON数组。我想让这个json数组到android应用程序并将其转换为java数组。如果你能帮上忙,那会很棒。谢谢。 –
可能的重复:http://stackoverflow.com/questions/2255220/how-to-parse-a-json-and-turn-its-values-into-an-array –