简体   繁体   中英

Parse Hashtable in JSON, perfect(jsonencode). But I don't know how to parse json in Hashtable(jsondecode). (Android)

I've created a JSON encode where you enter a HashTable ( public Hashtable<?, ?> JSonDecode(String data) {... return objJS.toString(); } ) and get a string in JSON format. That is:

If I have a Hashtable with this (Hashtable in Hashtable):

Example 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);

I use my function( JSonEncode(exampleHT); ) and I get this string:

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

It works perfectly! My problem is to create the reverse process, with 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.

}

I do not know how to parse json in Hashtable, without indicating the tags manually. That is, without it:

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

This should be dynamic without knowing json content without writing manually Color, Countries, ....

Any ideas or advice? Thanks,

You can get an Iterator object (java.util.Iterator) over the keys of your JSONObject (jObject) So you can write something like this:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM