0

我创建了一个 JSON 编码,您可以在其中输入 HashTable ( public Hashtable<?, ?> JSonDecode(String data) {... return objJS.toString(); }) 并获取 JSON 格式的字符串。那是:

如果我有一个带有这个的哈希表(哈希表中的哈希表):

示例哈希表

Hashtable<String, Object> exampleHT = new Hashtable<String, Object>();
    exampleHT.put("Color", "Red");
    exampleHT.put("OtherKey", "OtherValue");
    exampleHT.put("OtherKey2", "OtherValue2");

Hashtable<String, Object> country = new Hashtable<String, Object>();
    country.put("Spain", "Madrid");
    country.put("France","Paris");
    country.put("Italy", "Rome");

Hashtable<String, String> pokemon = new Hashtable<String, String>();
    pokemon.put("Pikachu", "Electric");
    pokemon.put("Charmander","Fire");

country.put("Pokemons", pokemon);

exampleHT.put("Countries", country);

我使用我的函数(JSonEncode(exampleHT);),我得到这个字符串:

{
    "Color":"Red",
    "Countries":{
        "Spain":"Madrid",
        "France":"Paris",
        "Italy":"Rome",
        "Pokemons":{
            "Pikachu":"Electric",
            "Charmander":"Fire"
        }
    },
    "OtherKey":"OtherValue",
    "OtherKey2":"OtherValue2"
}

它完美地工作!我的问题是使用JSonDecode创建反向过程。

Hashtable<?, ?> hashUnknown = JSonDecode(jsonStringExample);

public Hashtable<?, ?> JSonDecode(String data) {
 // I do not know how to parse json in Hashtable, without indicating the tags manually.

}

我不知道如何在 Hashtable 中解析 json,而无需手动指示标签。也就是说,没有它:

JSONArray menuObject = new JSONArray (jObject.getString ("Color"));
JSONArray menuObject = new JSONArray (jObject.getString ("Countries"));

  这应该是动态的,不知道 json 内容而无需手动编写颜色、国家、...。

有什么想法或建议吗?谢谢,

4

1 回答 1

1

您可以通过 JSONObject (jObject) 的键获取 Iterator 对象 (java.util.Iterator) 所以您可以编写如下内容:

Iterator<String> it = jObject.keys();
String key = null;
Object value = null;
while (it.hasNext()) {
    key = it.next();
    value = jObject.get(key);
    // Then test the instance of the value variable
    // and perform some logic
}
于 2013-05-14T19:00:16.830 回答