我試圖通過將回應轉換為 json 來做到這一點,然后找到它的歸檔形式。
但是我既不知道如何將其轉換為json,也不知道如何遍歷json。
@POST
@Path("/custoemrs")
@Produces({ MediaType.APPLICATION_JSON })
Response createCustomer(Customer customer);
會有一個我想提取的 id 欄位。
那里有太多答案,我嘗試了其中一些,但沒有一個有效。
我想用jackson來處理json檔案,我用的是resteasy客戶端。
我正在使用的回應是 javax.ws.rs.core.Response,請基于此回答
我看到很多人說類似
EntityUtils.toString(entity)
但我什至無法解決 entityutils ......
uj5u.com熱心網友回復:
ObjectMapper 是 Jackson 的核心類,使用它。無需將任何內容轉換為字串,Jackson 可以直接從 HTTP 輸入流中讀取。
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
public class ParseJSON {
public static void main(String[] args) throws IOException {
InputStream streamFromServer = streamFromServer; //Wherever this comes from
final JsonNode jsonNode = new ObjectMapper().readTree( streamFromServer );
final String yourValue = jsonNode.at( "/path/to/your/value" ).asText();
}
}
uj5u.com熱心網友回復:
雖然我不確定你的Customer物件是什么樣子,但下面可能對你有幫助:
String customer = EntityUtils.toString(entity); // returns your customer in String format.
ObjectMapper mapper = new ObjectMapper(); // this is com.fasterxml.jackson.databind.ObjectMapper class
HashMap<?, ?> map = mapper.readValue(customer, HashMap.class);
System.out.println(map.get("id")); // extracting id field.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/530170.html
標籤:爪哇休息http响应
