我想使用GSON将对象转换为json字符串。json字符串是
"type": "both", "value": ["numbercodes", [1, 2, 3]]
如您所见,“值”是字符串列表,后跟整数数组,因此如何表示字符串和数字的异类列表
以下代码不起作用:
class X
{
String type;
List<List<String>> value;
}
或什至以下代码将无法正常工作:
class Value
{
String x1;
List<Integer> x2;
}
class X
{
String type;
Value value;
}
和:
Gson gson = new Gson();
X x = new X();
String jsonString = gson.toString(x);
但是jsonString的值不会像预期的那样。
“ type”:“ both”,“ value”:[“ numbercodes”,[1、2、3]
那么我应该如何定义我的类“ X”,以便使我高于json字符串。
最好的解决方案是重构数据模型。始终编写对其他开发人员明确的代码,以便他们可以理解模型所代表的含义。它应该类似于以下示例:
{
"type": "both",
"someKey": "numbercodes",
"arrayOfIntegers": [1, 2, 3]
}
然后,您的实体类将是:
class Entity {
String type;
String someKey;
List<Integer> arrayOfIntegers;
}
当前模型并没有真正说明什么是“数字代码”和整数数组。您可以通过多种方式进行更改,我刚刚提出了一种。
编辑:
如果您真的想保留当前模型,则应该是:
class Entity {
String type;
List<Object> value = new ArrayList<>();
...
public void addValue(Object valueToAdd){
value.add(valueToAdd);
}
}
...
Entity entity = new Entity();
entity.setType("both");
entity.addValue("numbercodes");
entity.addValue(Arrays.asList(1,2,3));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句