1

这是 JSON 字符串 1

{"title":["1","2"], "amount":["1","2"]}

这是 JSON 字符串 2

{"title":"", "amount":""}

字符串 1 是在我在表单中输入值时创建的,而字符串 2 是在我不输入时创建的,我想知道字符串是格式 1 的标题是数组 ["1", "2"] 还是格式 2在我解析它之前,标题只是 servlet 中服务器端的字符串“”。有什么办法吗?

这是我之前的问题, 如何在 servlet 中使用 GSON 解析这个 JSON 字符串

这已解决,但正如您所见,我有类 Data,它具有 ArrayList 类型的实例变量,所以当我用这一行解析它时

Data data = gson.fromJson(param, Data.class);

它抛出异常

 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 24

因为正如我声明的 ArrayList,它只期望 json 中的数组来解析它,没有任何异常......但是当我不在我的表单中输入值时,它不会创建 json 字符串为

{"title":[], "amount":[]}

而是像这样创建

{"title":'', "amount":''}

以字符串为值,导致解析抛出异常

4

2 回答 2

3

也有这个问题,这就是我解决它的方法

在您的数据对象中有

public class Data {
    // This is a generic object whose type is determined when used by GSON
    private Object title;

    // get the type of object and return as string
    public String getTitleObjType() {
            String objType = title.getClass().toString();
        return objType;
    }

    // used if the object is an ArrayList, convert into an ArrayList<Object>
    public ArrayList<String> getTitleArrayList() {
        // Turn the Object into an arraylist
        @SuppressWarnings("unchecked")  // This is to counter the fact that the cast is not type safe
        ArrayList<String> titleArrayList = (ArrayList<String>) title;
        return titleArrayList;
    }

    // used if the object is not an array
    public String getTitleStr() {
            return title.toString();
    }
}

当 GSON 构建它将创建的对象时,每个对象都是 String 或 ArrayList

然后当你想使用这些对象时,测试看看它们是什么

ArrayList<String> titleValArrayList = new ArrayList<String>();
String titleValStr = "";

if(getTitleObjType.equals("class java.util.ArrayList")) {
         titleValArrayList = getTitleArrayList();
         //do whatever you like
}
else if(getTitleObjType.equals("class java.util.String")) {
         titleValStr = getsTitleStr();
         //do whatever you like
}
于 2013-07-15T05:55:20.030 回答
2

检查Google GSON,它允许您解析 JSON 服务器端。

它是这样的:

 String jsonString = request.getParameter("jsonParemeter");
 Gson gson = new Gson();
 Map fromJsonMap = gson.fromJson(jsonString, HashMap.class);

 Object object = fromJsonMap.get("title");
 if (object instanceof Collection) {
  // then is it's your array
 }
 else {
   // it's not
 } 

例如,如果我运行以下示例代码:

String json1 = "{\"title\":[\"1\",\"2\"], \"amount\":[\"1\",\"2\"]}";
String json2 = "{\"title\":\"\", \"amount\":\"\"}";

Gson gson = new Gson();
HashMap map = gson.fromJson(json1, HashMap.class);
HashMap map2 = gson.fromJson(json2, HashMap.class);

System.out.println(map);
System.out.println(map2);

System.out.println(map.get("amount").getClass());
System.out.println(map2.get("amount").getClass());

我得到输出:

{amount=[1, 2], title=[1, 2]}
{amount=, title=}
class java.util.ArrayList
class java.lang.String

如果我理解正确,我认为它适合你 100%

更新

由于您尝试将 JSON 字符串直接反序列化为 Data 对象,因此如果您想继续进行直接反序列化,则必须使用自定义反序列化机制

于 2012-11-30T18:29:50.623 回答