简体   繁体   中英

Convert Map<String, Object> from JSON

I'm currently writing a Spring based webservice application, where the result of the service call are supposed to be sent using a rather generic class ActionReply . This class contains a private Map<String, Object> parameters = new HashMap<>(); where the objects, that are retrieved from a database can be stored. Now the value can be actually any kind of class, but mostly a subclass of my base class BaseObject . The problem I'm facing now is that the returned JSON string when I try to get Locale objects stored in that map as value looks like this:

reply: <200,{"parameters":{"DATA":["de_DE"]},"successful":true,"errorMessage":null,"subsequentContext":null},{Content-Type=[application/json;charset=UTF-8], Transfer-Encoding=[chunked], Date=[Sun, 09 Dec 2018 13:15:21 GMT]}>So 

So basically that's fine, however the locale object is interpreted as String, which seems normal, because there is no information about the Locale class in the JSON string. So my question is, how can I pass that information or what do I have to do when creating from/to the Map that I get Locale objects and not String objects?

Thanks!

Maybe I'm not following you properly, but if you get the Locale on a String and you want the Locale object, you have to do something like this:

Locale myLocale = new Locale(myRetrievedLocaleString);

In the other side, it seems you are not getting a valid JSON object, however if you just need the locale and you cannot extract it, then do something like this:

String jsonLocale = response.substring(0,32) + "}";

That way you will get a valid json on a String, now you'll be able convert it successfully to a JSON object and extract the locale object.

I found a solution based on JSONPath:

<dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>2.3.0</version>
    </dependency>

The following code snippet works fine for me:

public static Object extractParametersData(Type type, String json)
{
    Gson gson = new Gson();
    HashMap<String, JSONArray> data = JsonPath.read(json, "$.parameters");

    return gson.fromJson(String.valueOf(data.get("DATA")), type);
}

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