收到使用GSON JSON对象的键名(get key names from JSON object

2019-08-18 09:50发布

我有一个JSON对象,我想摆脱键名,并将它们存储在一个ArrayList。 我用下面的代码

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

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

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

这工作得很好。 年龄,姓名和消息(不是值)被添加到我的ArrayList。 有一次,我尝试使用相同的代码,像这样一个比较复杂的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;"
    }
}}

我只得到根密钥。 有人能指出我在这个正确的方向?

感谢大家!

Answer 1:

相反,通过与循环和条件的GSON(JSON)API蜿蜒的,我宁愿使用GSON什么,我认为它最擅长的:提供了非常简单的(反)序列化处理,只需几行代码。 我会去耦从(反)序列关心的任何数据操作/查询/表示担忧。 换句话说,尽可能合理,操作数据在必要时,序列化之前,同样,操作数据在必要时,反序列化之后。

因此,如果由于某种原因,我想所有的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
        }]
    }
}]


文章来源: get key names from JSON object using Gson