noisy cat
noisy cat

Reputation: 3065

Java decode JSON

Im trying to decode json string to Map.

I know there were many questions like this, but I need quite specific format. For example, I have json string:

{
    "map": {
        "a": "b",
        "c": "d",
    },
    "map2": {
        "aa": "bb",
        "cc": "dd",
    },
    "something": "a",
    "something2": "b"
}

And I need to have results like:

"map.a" => "b"
"map.c" => "d"
"map2.aa" => "bb"
"map2.cc" => "dd"
"something" => "a"
"something2" => "b"

Im sure that the keys won't contain any dots. I looked at few JSON libraries, but I don't need so many functions, just to decode and store in Java map. If there is no simple way, I gonna write own algorithm for this, I hope it won't be so hard...

Thanks for any help.

Upvotes: 0

Views: 458

Answers (3)

anvarik
anvarik

Reputation: 6487

I used org.codehaus.jackson. Do the following:

    HashMap<String, Object> content = null;
    HashMap<String, String> result = new HashMap<String, String>();

    try {
        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper(factory);
        TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
        };
        content = mapper.readValue(jsonString, typeRef);

    } catch (Exception ex) {
        System.out.println("Exception : " + ex);
    } 
    // now content has everything inside
    for(String s : content.keySet()){
        Object obj = content.get(s);
        if(obj instanceof String){
            result.put(s, (String)obj);
        } else {
            HashMap<String,String> hm = (HashMap<String,String>)obj;
            for(String s2: hm.keySet()){
                result.put(s+"."+s2, hm.get(s2));
            }

        }
    }

Edit: Tested, and working

Upvotes: 1

Jimothy
Jimothy

Reputation: 9750

I don't think you'll find an out-of-the-box solution to this, since that's a non-standard representation. My suggestion would be to use a JSON library to convert the JSON string to a Java Map, then do a depth-first traversal of that Map to transform it to your desired representation.

Upvotes: 1

Brandon Buck
Brandon Buck

Reputation: 7181

To accurately parse JSON you'll want to define a proper parser for it, they're not terribly difficult to write just time consuming. My recommendation would be to find a fairly lightweight JSON parser and then write a decorator for it to get the map format you're looking for. Although, if you're processing large amounts of JSON you'll, unfortunately, be adding overhead.

Upvotes: 1

Related Questions