与其在Gson(JSON)API中使用循环和条件,我更愿意使用Gson实现我认为它最棒的功能:只需几行代码即可实现非常简单的(反)序列化处理。我愿意
decouple
来自(反)序列化问题的任何数据操作/查询/表示问题。换句话说,在合理的情况下,在序列化数据之前,根据需要对数据进行操作,类似地,在反序列化数据之后,根据需要进行操作。
因此,如果出于某种原因,我想要JSON结构中的所有键,并且我想使用Gson,我可能会按照如下方式处理。(当然,我目前想不出为什么这样的东西会有用。)
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
public class App
{
public static void main(String[] args) throws Exception
{
List keys1 = getKeysFromJson("input_without_lists.json");
System.out.println(keys1.size());
System.out.println(keys1);
List keys2 = getKeysFromJson("input_with_lists.json");
System.out.println(keys2.size());
System.out.println(keys2);
}
static List getKeysFromJson(String fileName) throws Exception
{
Object things = new Gson().fromJson(new FileReader(fileName), Object.class);
List keys = new ArrayList();
collectAllTheKeys(keys, things);
return keys;
}
static void collectAllTheKeys(List keys, Object o)
{
Collection values = null;
if (o instanceof Map)
{
Map map = (Map) o;
keys.addAll(map.keySet()); // collect keys at current level in hierarchy
values = map.values();
}
else if (o instanceof Collection)
values = (Collection) o;
else // nothing further to collect keys from
return;
for (Object value : values)
collectAllTheKeys(keys, value);
}
}
input_without_lists.json输入
{
"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
}
input_with_lists.json输入
[{
"widget": {
"debug": "on",
"windows": [{
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},{
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},{
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
}]
}
}]