使用Gson从JSON对象获取键名 [英] get key names from JSON object using Gson

查看:837
本文介绍了使用Gson从JSON对象获取键名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON对象,我想从中获取键名并将它们存储在一个ArrayList中。我使用了下面的代码:

$ p $ jsonData(String filename){
JsonParser parser = new JsonParser();
JsonElement jsonElement = null;

尝试{
jsonElement = parser.parse(new FileReader(filename));
} catch(JsonIOException | JsonSyntaxException | FileNotFoundException e){
// TODO自动生成的catch块
e.printStackTrace();
}

JsonObject jsonObject = jsonElement.getAsJsonObject();

int i = 0;
for(Entry< String,JsonElement> entry:jsonObject.entrySet()){
String key = entry.getKey();
JsonElement value = entry.getValue();

keys.add(key);
i ++;
}
nKeys = i;
}

如果我用一个简单的JSON对象使用这段代码

  {
age:100,
name:mkyong.com,
messages :[msg 1,msg 2,msg 3]
}

这工作正常。年龄,名称和消息(而不是值)被添加到我的ArrayList。一旦我尝试和使用这个相同的代码与这样一个更复杂的JSON

  {widget:{
debug:on,
窗口:{
title: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;
}
}}

我只得到root密钥。有人可以指出我正确的方向吗?



谢谢大家!

解决方案

我没有使用Gson(JSON)API使用循环和条件来蜿蜒曲折,而是倾向于使用Gson来实现我认为最好的做法:使用几行代码提供非常简单的(de)序列化处理。我将解耦关于序列化问题的任何数据操纵/查询/表示问题。换句话说,尽可能合理,在序列化之前根据需要操作数据,并且类似地,在反序列化之后根据需要操作数据。所以,如果出于某种原因,我想要从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;
$ b $ 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);

列表keys2 = getKeysFromJson(input_with_lists.json);
System.out.println(keys2.size());
System.out.println(keys2);


静态列表getKeysFromJson(String fileName)抛出异常
{
Object things = new Gson()。fromJson(new FileReader(fileName),Object.class );
List keys = new ArrayList();
collectAllTheKeys(键,东西);
返回键;


static void collectAllTheKeys(List keys,Object o)
{
Collection values = null;
if(o instanceof Map)
{
Map map =(Map)o;
keys.addAll(map.keySet()); //收集当前级别的键在层次结构中
values = map.values();
}
else if(o instanceof Collection)
values =(Collection)o;
else //没有进一步从
收集密钥return;

for(Object value:values)
collectAllTheKeys(keys,value);
}
}

input_without_lists.json

  {
widget:{
debug:on,
窗口:{
title:示例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;



code
$ b

input_with_lists.json <

  [{
widget:{
debug:on ,
windows:[{
title:Konfabulator Widget示例,
name:main_window,
width:500,
height:500
} {b $ btitle:Konfabulator Widget示例,
name:main_window,
width:500,
height:500
},{
title:Konfabulator Widget示例,
name:main_window,
width:500 ,
height:500
}]
}
}]


I have a JSON object that I'd like to get the key names from and store them in an ArrayList. I've used the following code

jsonData(String filename) {
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = null;

    try {
        jsonElement = parser.parse(new FileReader(filename));
    } catch (JsonIOException | JsonSyntaxException | FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    JsonObject jsonObject = jsonElement.getAsJsonObject();

    int i = 0;
    for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        String key = entry.getKey();
        JsonElement value = entry.getValue();

        keys.add(key);
        i++;
    }
    nKeys = i;
}

If I use this code with a simple JSON object

{
    "age":100,
    "name":"mkyong.com",
    "messages":["msg 1","msg 2","msg 3"]
}

This works fine. age, name, and messages (not the values) are added to my ArrayList. Once I try and Use this same code with a more complex JSON like this

{"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;"
    }
}}

I only get the root key. Can someone point me in the right direction with this?

Thanks everyone!

解决方案

Instead of meandering through the Gson (JSON) API with loops and conditionals, I'd prefer to use Gson for what I think it does best: provide for very simple (de)serialization processing with just a few lines of code. I'd decouple any data manipulation/querying/presentation concerns from the (de)serialization concern. In other words, as much as reasonable, manipulate the data as necessary, before serializing it, and similarly, manipulate the data as necessary, after deserializing it.

So, if for some reason I wanted all of the keys from a JSON structure, and I wanted to use Gson, I'd likely approach it as follows. (Of course, I cannot currently think of any reason why such a thing could be useful.)

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
        }]
    }
}]

这篇关于使用Gson从JSON对象获取键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆