Your conversion of JSON to Java largely depends on which library you are using to perform the task. The other answers here use the org.json
library, but most geeks will react violently over its usage because it's quite slow. The fastest library I know of is Jackson, but I personally prefer Google-GSON because it's fast enough and yet remains very easy to use.
Looking at your sample string, you seem to have an array of arrays of strings. In Gson, you want to think of them as a Collection
of a Collection
of String
s. Here's the sample code:
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();
}
}
}
And the output:
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,
This is taken from the Google-GSON user guide: https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples