我创建了一个JSON编码,您在其中输入HashTable (public Hashtable<?, ?> JSonDecode(String data) {... return objJS.toString(); }
)并获得JSON格式的字符串。即:
如果我有一个Hashtable with this (Hashtable in Hashtable):
例子Hashtable :
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.
}
我不知道如何在哈希表中解析json,而不手动指示标签。也就是说,没有它:
JSONArray menuObject = new JSONArray (jObject.getString ("Color"));
JSONArray menuObject = new JSONArray (jObject.getString ("Countries"));
这应该是动态的,不需要知道json内容,不需要手动编写颜色,国家,....
有什么想法或建议吗?谢谢你,
您可以在JSONObject (jObject)的键上获得一个迭代器对象(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
}