简体   繁体   English

转换地图 <String, Object> 从JSON

[英]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 . 我目前正在编写一个基于Spring的Web服务应用程序,该服务调用的结果应该使用相当普通的类ActionReply发送。 This class contains a private Map<String, Object> parameters = new HashMap<>(); 此类包含一个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 . 现在,该值实际上可以是任何类型的类,但主要是我的基类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: 我现在面临的问题是,当我尝试获取存储在该地图中的Locale对象作为值时,返回的JSON字符串如下所示:

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. 因此基本上可以,但是将语言环境对象解释为String,这看起来很正常,因为JSON字符串中没有有关Locale类的信息。 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? 所以我的问题是,当从/到创建了Locale对象而不是String对象的Map进行创建时,如何传递该信息或该怎么办?

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: 另一方面,似乎您没有获得有效的JSON对象,但是,如果仅需要locale且无法提取它,则可以执行以下操作:

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. 这样,您将在String上获得有效的json,现在您可以将其成功转换为JSON对象并提取语言环境对象。

I found a solution based on JSONPath: 我找到了基于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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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