【问题标题】:How to parse jquery.sheet's JSON in Java?如何在 Java 中解析 jquery.sheet 的 JSON?
【发布时间】:2012-05-24 15:05:57
【问题描述】:

我正在使用接受JSON 的 jquery.sheet 插件。 JSON 格式为:

[
    { //repeats
        metadata: {
            columns: Column_Count,
            rows: Row_Count,
            title: ''
        },
        data: {
            r{Row_Index}: { //repeats
                c{Column_Index}: { //repeats
                    value: '',
                    style: '',
                    width: 0,
                    cl: {Classes used for styling}
                }
            }
        }
    }
]; 

一个简单的例子可能是:

[
    { 
        metadata: {
            columns: 1,
            rows: 1,
            title: 'Private Limited'
        },
        data: {
            r0: { 
                c0: { 
                    value: 'A',
                    style: '',
                    width: 0
                }
            }
        }
    }
]

我需要在Java 中解析这个JSON?我知道我可以使用 google 的 gson 库进行解析。但我不知道该怎么做。

【问题讨论】:

  • 不好的是行和列名不一致,r0、r1、r2、c0、c1、c2等

标签: java jquery json spring-mvc


【解决方案1】:

严格来说,您所指的示例不是有效的JSON,例如它在metadata [根据 www.json.org 中定义的 JSON][http://json.org/]

的字段 ID 周围缺少“”

出于这个原因我建议在将其传递给Java(例如 servlet)之前,您应该将该对象字符串化,例如as shown in this answer。这样您就可以确定这是一个有效的JSON。稍后使用jQuery 将其发送到servlet。在您的Java 代码中,您使用以下代码将您的json 字符串转换为JSONArray,您将在该代码上进一步操作。

String json = request.getParameter(param);
JSONArray jsonArray = new JSONArray(json);

然后您可以像遍历任何其他集合一样遍历它的元素。

for (int i = 0; i < jsonArray.length(); i++) {
   JSONObject jsonObject = jsonArray.getJSONObject(i);
   //work with the jsonObject
}

The JSONArray and JSONObject classes are taken from here.

The jar for the library is availalbe here.

如果您愿意,可以使用gson。尽管在这种特殊情况下,这个库就足够了。如果我有一个对应JSON 字符串的bean 对象,我个人使用gson,否则json.org 绰绰有余。

【讨论】:

    猜你喜欢
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多