转换JSON代码的最佳方法是什么:

{ 
    "data" : 
    { 
        "field1" : "value1", 
        "field2" : "value2"
    }
}

在Java Map中,其中一个键是(field1, field2),这些字段的值是(value1, value2)。

什么好主意吗?我应该使用Json-lib吗?或者如果我自己编写解析器会更好?


当前回答

使用GSON库:

import com.google.gson.Gson;
import com.google.common.reflect.TypeToken;
import java.lang.reclect.Type;

使用以下代码:

Type mapType = new TypeToken<Map<String, Map>>(){}.getType();  
Map<String, String[]> son = new Gson().fromJson(easyString, mapType);

其他回答

如果你需要没有任何依赖的纯Java,你可以使用Java 8中内置的Nashorn API。在Java 11中已弃用。

这对我来说很管用:

...
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
...

public class JsonUtils {

    public static Map parseJSON(String json) throws ScriptException {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByName("javascript");

        String script = "Java.asJSONCompatible(" + json + ")";

        Object result = engine.eval(script);

        return (Map) result;
    }
}

示例使用

JSON:

{
    "data":[
        {"id":1,"username":"bruce"},
        {"id":2,"username":"clark"},
        {"id":3,"username":"diana"}
    ]
}

代码:

...
import jdk.nashorn.internal.runtime.JSONListAdapter;
...

public static List<String> getUsernamesFromJson(Map json) {
    List<String> result = new LinkedList<>();

    JSONListAdapter data = (JSONListAdapter) json.get("data");

    for(Object obj : data) {
        Map map = (Map) obj;
        result.add((String) map.get("username"));
    }

    return result;
}

我这样做。这很简单。

import java.util.Map;
import org.json.JSONObject;
import com.google.gson.Gson;

public class Main {
    public static void main(String[] args) {
        JSONObject jsonObj = new JSONObject("{ \"f1\":\"v1\"}");
        @SuppressWarnings("unchecked")
        Map<String, String> map = new Gson().fromJson(jsonObj.toString(),Map.class);
        System.out.println(map);
    }
}
import net.sf.json.JSONObject

JSONObject.fromObject(yourJsonString).toMap

另一个选择是json-simple,可以在Maven Central中找到:

(JSONObject)JSONValue.parse(someString); //JSONObject is actually a Map.

工件是24kbytes,没有其他运行时依赖项。

我喜欢图书馆。 当你不知道json的结构。你可以使用

JsonElement root = new JsonParser().parse(jsonString);

然后你可以使用json。例如,如何从你的gson中获取"value1":

String value1 = root.getAsJsonObject().get("data").getAsJsonObject().get("field1").getAsString();