簡體   English   中英

Java中JSONObject內的JSONobject

[英]JSONobject inside JSONObject in java

我有以下請求映射:

@RequestMapping(value = "/reCalculated", method = RequestMethod.POST)
public @ResponseBody void reCalculated(JSONObject obj) {

    obj.
}

然后我有傳入的json

{"params":{"date_a":"2017-05-01","date_b":"2017-05-02"}}

但在Java中, obj. 同時,在所有教程中,只給我提供了toString()toJSONString()選項,並且很少有線程清楚地告訴我我應該能夠做到obj.getJSONObject("params")為什么會這樣? 如何訪問我的參數?

<dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1.1</version>
 </dependency>

是依賴性。

json-simple庫具有方法get(String name)並且需要外部類型轉換,如下所示

String name = (String) jsonObject.get("name");
JSONArray msg = (JSONArray) jsonObject.get("messages");
long age = (Long) jsonObject.get("age");

但是gson在這里有預定義的方法

public JsonObject getAsJsonObject(String memberName)
public JsonArray getAsJsonArray(String memberName)

Maven依賴

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.3</version>
</dependency>

您可以從參數中獲取JSONString

Gson gson = (new GsonBuilder()).create();
jsonString = obj.get("params").getAsString();
JsonObject param= gson.fromJson(jsonString, JsonObject.class);

正如Deadpool所說,您想使用gson但添加了json-simple依賴項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM