我创建了一个JSON编码,您可以在其中输入HashTable(public Hashtable<?, ?> JSonDecode(String data) {... return objJS.toString(); }
)并获取JSON格式的字符串。那就是:
如果我有一个Hashtable(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.
}
我不知道如何在Hashtable中解析json,而不是手动指示标记。 也就是说,没有它:
JSONArray menuObject = new JSONArray (jObject.getString ("Color"));
JSONArray menuObject = new JSONArray (jObject.getString ("Countries"));
如果不手动编写Color,Countries,....,这应该是动态的,不知道json内容。
任何想法或建议?谢谢,
答案 0 :(得分: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
}