【问题标题】:Best practice to receive JSON and convert it to an object接收 JSON 并将其转换为对象的最佳实践
【发布时间】:2014-04-13 06:37:40
【问题描述】:

我在 java 中接收到一个 JSON 字符串,我希望将其转换为表示该字符串的对象。 我目前有这个功能:

private ArrayList<MyDevice> parseResposne(String response) {
    ArrayList<MyDevice> devices = null;
    JSONArray jsnArr = null;
    try {
        // JSONObject jObj = new JSONObject(response);
        jsnArr = new JSONArray(response);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    for (int i = 0; i < jsnArr.length(); i++) {
         MyDevice tmpDevice = new MyDevice(jsnArr.);
        // devices.add(tmpDevice);
    }

    return null;
}

这是我的 Mydevice 类:

public class MyDevice {

public String name;
public int deviceId;
public String serialNo;
public String deviceType;
public boolean enabled;

public MyDevice(int deviceId, String name, String serialNo, String deviceType, boolean enabled) {
    this.deviceId = deviceId;
    this.name = name;
    this.serialNo = serialNo;
    this.deviceType = deviceType;
    this.enabled = enabled;
}
}

有没有更简单的方法比如model binder ins asp.net mvc?

将 json 转换为对象的标准/最佳方法是什么?

【问题讨论】:

标签: java android json json.net


【解决方案1】:

您可以使用 Google 的 Gson 库轻松将 json 转换为 Object,反之亦然。

Gson gson = new Gson();
ArrayList<MyDevice> yourArray = gson.fromJson(jsonString, new TypeToken<List<MyDevice>>(){}.getType());


public class MyDevice {

    public String name;
    public int deviceId;
    public String serialNo;
    public String deviceType;
    public boolean enabled;

   //Setters and Getters
}

【讨论】:

    【解决方案2】:

    如果你有一个复杂的 json 或大量的数据,你最好使用 Gson 来映射数据和你的模型类。例如:

        Gson gson = new Gson();
        ModelClass modelClass= new ModelClass();
        modelClass= gson.fromJson(responseContent,ModelClass.class); 
    //where responseContent is your jsonString
        Log.i("Web service response", ""+modelClass.toString());
    

    https://code.google.com/p/google-gson/

    对于命名差异(根据webservice中的变量),可以使用如下注解 @SerializedName。 (所以不需要使用Serializable

    【讨论】:

    • 关于 Gson 值得注意的一点是它对无效 JSON 文档的处理是多么糟糕——通常,它会尝试在没有任何警告的情况下解析它们。更改此行为可能非常麻烦。
    • @kamituel 如果 JSON 无效,我认为处理它的工作将非常相似,无论方法如何:)。我认为验证 JSON 不是“解析器”的责任,尽管 Jackson 或任何其他库是否提供无效的 json 处理?
    • 我希望解析器(至少)能够在输入不是 JSON 文档的字符串时抛出错误。
    • 如果您想尝试解决方案,您可以在将其提供给解析器之前通过检查它是 JSONObject 还是 com.google.gson.JsonElement 来手动验证 json
    • 但是我会有效地解析同一个文档两次。我的观点是解析库至少应该警告输入无效。
    【解决方案3】:

    您可以查看 GSON/Jackson 等流式解析器。

    【讨论】:

    • 这应该是评论!
    猜你喜欢
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    相关资源
    最近更新 更多