Rest Assured: extract value from Response List - java

I have a List returned as response. I need to get one item from list using product.name and tariffPlan.name.
[
{
"id": 123,
"product": {
"id": 1,
"code": "credit",
"name": "Credit"
},
"tariffPlan": {
"id": 1,
"code": "gold",
"name": "Gold"
}
},
{
"id": 234,
"product": {
"id": 2,
"code": "debit",
"name": "Debit"
},
"tariffPlan": {
"id": 1,
"code": "gold",
"name": "Gold"
}
}
]
I use Java8. Here is my method. I got List of Card.class elements. And then I need to get single Item from list with specified "product.name" and "tariffPlan.name".
public List<Card> getCardId(String productName, String tariffPlanName) {
return given()
.param("product.name", productName)
.param("tariffPlan.name", tariffPlanName)
.when().get("/").then()
.extract().jsonPath().getList("", Card.class);
}
Is it possible to do it with restAssured? Maybe use .param method like in my example? But in my example .param method is ignored. Thank you for your ideas.
UPD. My decision is:
public Card getCard(String productName, String tariffPlanName) {
List<Card> cardList = given()
.when().get("/").then()
.extract().jsonPath().getList("", Card.class);
return cardList.stream()
.filter(card -> card.product.name.equals(productName))
.filter(card -> card.tariffPlan.name.equals(tariffPlanName))
.findFirst()
.get();
}

If you need to get a value from response json list, here's what worked for me:
Json sample:
[
{
"first": "one",
"second": "two",
"third": "three"
}
]
Code:
String first =
given
.contentType(ContentType.JSON)
.when()
.get("url")
.then()
.extract().response().body().path("[0].first")

Actually, you can but... you need to handle deserialization issue of default mapper becase if you try do the following:
.extract().jsonPath().getList("findAll {it.productName == " + productName + "}", Card.class);
You will failing on converting HashMap to your object type. It happens because of using gpath expression in path provides json without double quotes on keys by default. So you need to prettify it with (you can put it in RestAssured defaults):
.extract().jsonPath().using((GsonObjectMapperFactory) (aClass, s) -> new GsonBuilder().setPrettyPrinting().create())
And as result your would be able to cast things like that:
.getObject("findAll {it.productName == 'productName'}.find {it.tariffPlanName.contains('tariffPlanName')}", Card.class)
See full example:
import com.google.gson.GsonBuilder;
import io.restassured.http.ContentType;
import io.restassured.mapper.factory.GsonObjectMapperFactory;
import lombok.Data;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.List;
import static io.restassured.RestAssured.given;
public class TestLogging {
#Test
public void apiTest(){
List<Item> list = given()
.contentType(ContentType.JSON)
.when()
.get("https://jsonplaceholder.typicode.com/posts")
.then().log().all()
.extract().jsonPath().using((GsonObjectMapperFactory) (aClass, s) -> new GsonBuilder().setPrettyPrinting().create())
.getList("findAll {it.userId == 6}.findAll {it.title.contains('sit')}", Item.class);
list.forEach(System.out::println);
}
#Data
class Item {
private String userId;
private String id;
private String title;
private String body;
}
}

Here a kotlin example:
#Test
fun `creat endpoint with invalid payload should return 400 error`() {
val responseError: List<ErrorClass> = Given {
spec(requestSpecification)
body(invalidPayload)
} When {
post("/endpoint")
} Then {
statusCode(HttpStatus.SC_BAD_REQUEST)
} Extract {
body().`as`(object : TypeRef<List<ErrorClass>>() {})
}
responseError shouldHaveSize 1
responseError[0].field shouldBe "xxxx"
responseError[0].message shouldBe "xxx"
}

Suppose you want to fetch the value of the id, when product name is "Credit" and tariffPlan is "Gold".
Use
from(get(url).asString()).getList("findAll { it.product.name == 'Credit' && it.tariffPlan.name == 'Gold'}.id");
Where url - http/https request and get(url).asString() will return a JSON response as string.

Related

Concat a string with a function to get a JSON output

I just started using java for a project, and I have this doubt. I'm trying to get a JSON answer with this code, but I don't know how to concatenate a string with a function in Java Spring. I have this controller, with this result:
public class BbController {
#Autowired
BbService bbService;
private static final String RESP_SUCCESS = "{\"result\" : { \"status\": true, \"http_code\" : 200, \"info\": \"list successfully obtained.\"}}";
#RequestMapping(value= "/all", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getAllContracts() {
return RESP_SUCCESS + ",{" + this.bbService.getAllContracts() + "}";
}
}
<---------- RESULT --------->>>
{
"result": {
"status": true,
"http_code": 200,
"info": "list successfully obtained."
}
},
{
[com.example.entity.BbEntity#3ddd5cfb, com.example.entity.BbEntity#1a57ff51
]
}
Without the concatenation and just returning return this.bbService.getAllContracts(), the output would be
[
{
"id": 12345,
"id_client": 123,
"n_contracts": 2,
"default_number": 2
},
{
"id": 1,
"id_client": 12,
"n_contracts": 2,
"default_number": 2
}
]
My service would be
public class BbService {
#Autowired
BbDao bbDao;
public List<BbEntity> getAllContracts(){
return this.bbDao.findAll();
}
}
Is there any way to get this result?
{
"result": {
"status": true,
"http_code": 200,
"info": "list successfully obtained."
}
},
{
[
{
"id": 12345,
"id_client": 123,
"n_contracts": 2,
"default_number": 2
},
{
"id": 1,
"id_client": 12,
"n_contracts": 2,
"default_number": 2
}
]
}
Thanks in advance
Looks like this.bbService.getAllContracts() returns a class that does not implement toString(), therefor it gets this ugly default print, you can implement it to get the better represenataion that you want.
But I think the better solution should not be to fix the toString, but rather to change the return value of your method from a string to some class you create. If you're using spring, it will be serialized into json once you do it
if this.bbService.getAllContracts() , getAllContracts() returns the class it self, it will be autamatically serialized into Json.

How to modify the value of a JsonNode recursively using Jackson

Requirements:
I want to apply some functions on the inner values of the JsonNode. The functions can be different eg:- lowercasing some values or appending something to the values or replace the values with something. How can I achieve that using Jackson library? Note that the structure of the JSON data can be different which means I want to build a generic system which will accept some path expression which will basically decide where to change. I want to use functional programming style, so that I can pass these functions as arguments.
eg:
input:
{
"name": "xyz",
"values": [
{
"id": "xyz1",
"sal": "1234",
"addresses": [
{
"id": "add1",
"name": "ABCD",
"dist": "123"
},
{
"id": "add2",
"name": "abcd3",
"dist": "345"
}
]
},
{
"id": "xyz2",
"sal": "3456",
"addresses": [
{
"id": "add1",
"name": "abcd",
"dist": "123"
},
{
"id": "add2",
"name": "XXXXX",
"dist": "345"
}
]
}
]
}
In this case I have to two functions basically, lowercase() and convert_to_number(). I want to apply lowercase() function on all the "name" attribute inside all the "addresses" of each "value".
same goes for convert_to_number() , but for all the "dist" attribute.
So, basically the JSON expressions will be something like below for the functions:
lowercase() : /values/*/addresses/*/name
convert_to_number() : /values/*/addresses/*/dist
output:
{
"name": "xyz",
"values": [
{
"id": "xyz1",
"sal": "1234",
"addresses": [
{
"id": "add1",
"name": "abcd",
"dist": 123
},
{
"id": "add2",
"name": "abcd3",
"dist": 345
}
]
},
{
"id": "xyz2",
"sal": "3456",
"addresses": [
{
"id": "add1",
"name": "abcd",
"dist": 123
},
{
"id": "add2",
"name": "xxxx",
"dist": 345
}
]
}
]
}
Client code:
JsonNode jsonNode = ...
applyFunctionsRecursivelyBasedOnExpr(JsonNode jsonNode, String expr, Function )
As #MichalZiober in his answer already pointed out,
JsonPath offers a much more powerful API than Jackson,
when you need to do JSON-path-based operations.
Using methods JsonPath.parse and WriteContext.map
you can solve your problem in just a few lines:
import java.io.File;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("input.json");
String json = JsonPath.parse(file)
.map("$.values[*].addresses[*].name", Main::lowerCase)
.map("$.values[*].addresses[*].dist", Main::convertToNumber)
.jsonString();
System.out.println(json);
}
private static Object lowerCase(Object currentValue, Configuration configuration) {
if (currentValue instanceof String)
return ((String)currentValue).toLowerCase();
return currentValue;
}
private static Object convertToNumber(Object currentValue, Configuration configuration) {
if (currentValue instanceof String)
return Integer.valueOf((String)currentValue);
return currentValue;
}
}
JsonPath
You could use JsonPath library which has a better JSON Path handling. When Jackson supports only JSON Pointer draft-ietf-appsawg-json-pointer-03. Take a look on JsonPointer documentation. With JsonPath library you could do that in this way:
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import net.minidev.json.JSONArray;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public class JsonPathApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
JsonModifier jsonModifier = new JsonModifier(jsonFile);
Function<Map<String, Object>, Void> lowerCaseName = map -> {
final String key = "name";
map.put(key, map.get(key).toString().toLowerCase());
return null;
};
Function<Map<String, Object>, Void> changeDistToNumber = map -> {
final String key = "dist";
map.put(key, Integer.parseInt(map.get(key).toString()));
return null;
};
jsonModifier.update("$.values[*].addresses[*]", Arrays.asList(lowerCaseName, changeDistToNumber));
jsonModifier.print();
}
}
class JsonModifier {
private final DocumentContext document;
public JsonModifier(File json) throws IOException {
this.document = JsonPath.parse(json);
}
public void update(String path, List<Function<Map<String, Object>, Void>> transformers) {
JSONArray array = document.read(path);
for (int i = 0; i < array.size(); i++) {
Object o = array.get(i);
transformers.forEach(t -> {
t.apply((Map<String, Object>) o);
});
}
}
public void print() {
System.out.println(document.jsonString());
}
}
Your path, should work on JSON object-s which are represented by Map<String, Object>. You can replace keys in given object, add them, remove them just like replacing, adding and removing keys in Map.
Jackson
You can of course mock JsonPath feature by iterating over Json Pointer. For each * we need to create loop and iterate over it using counter and until node is not missing. Below you can see simple implementation:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
JsonNode root = mapper.readTree(jsonFile);
Function<ObjectNode, Void> lowerCaseName = node -> {
final String key = "name";
node.put(key, node.get(key).asText().toLowerCase());
return null;
};
Function<ObjectNode, Void> changeDistToNumber = node -> {
final String key = "dist";
node.put(key, Integer.parseInt(node.get(key).asText()));
return null;
};
JsonModifier jsonModifier = new JsonModifier(root);
jsonModifier.updateAddresses(Arrays.asList(lowerCaseName, changeDistToNumber));
System.out.println(mapper.writeValueAsString(root));
}
}
class JsonModifier {
private final JsonNode root;
public JsonModifier(JsonNode root) {
this.root = root;
}
public void updateAddresses(List<Function<ObjectNode, Void>> transformers) {
String path = "/values/%d/addresses/%d";
for (int v = 0; v < 100; v++) {
int a = 0;
do {
JsonNode address = root.at(String.format(path, v, a++));
if (address.isMissingNode()) {
break;
}
if (address.isObject()) {
transformers.forEach(t -> t.apply((ObjectNode) address));
}
} while (true);
if (a == 0) {
break;
}
}
}
}
This solution is slower than with JsonPath because we need to travers whole JSON tree n times where n number of matching nodes. Of course, our implementation could be a much faster using Streaming API.

Problem in parsing multiple json objects each having multiple Arrays from a validated JSON format-JavaString

Want to Process following JSON string (Validated with jsonlint.com)
[{
"label": "Hospital",
"domain": "Health_Care",
"synonymlabels": [{
"label": "SHCO"
}, {
"label": "HCO"
}],
"childrenlabels": [{
"label": "Childern_Hospital"
}, {
"label": "Mental_Hospital"
}, {
"label": "Heart_Hospital"
}, {
"label": "Orthopadic_Hospital"
}, {
"label": "General_Hospital"
}, {
"label": "Gynac_Hospital"
}, {
"label": "Cancer_Hospital"
}, {
"label": "Burn_Hospital"
}, {
"label": "Trauma_Care_Hospital"
}]
},
{
"label": "Doctor",
"domain": "Health_Care",
"synonymlabels": [{
"label": "Clinician"
}, {
"label": "Physician"
}, {
"label": "Medical_Practitioner"
}],
"childrenlabels": [{
"label": "Cardiaologist"
}, {
"label": "Allergist"
}, {
"label": "Nurologist"
}, {
"label": "Gynacologist"
}, {
"label": "General_Physician"
}, {
"label": "Anesthetist"
}, {
"label": "Physiotherapist"
}, {
"label": "Urologist"
}, {
"label": "Oncologist"
}, {
"label": "Homeopath"
}, {
"label": "Dentist"
}]
}
]
Sample Code
I am able to run the following sample code and able to get the desired output. If I change JSON string i.e. object "{}" to JSON ARRAY "[{},{},{}]" to parse and necessary change in the code (no idea that how to deal with the Array) then I'm getting no results in the console. Feeling paralytic in finding my error. Please help. Struggled for almost a day in tweaking the code.
import java.io.IOException;
import java.io.StringReader;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
public class gsontester {
public static void main(String args[]) {
String jsonString =
"{ \"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85,100,14,95]}";
JsonReader reader = new JsonReader(new StringReader(jsonString));
try {
handleJsonObject(reader);
}
catch (IOException e) {
e.printStackTrace();
}
}
private static void handleJsonObject(JsonReader reader) throws IOException {
reader.beginObject();
String fieldname = null;
while (reader.hasNext()) {
JsonToken token = reader.peek();
if (token.equals(JsonToken.BEGIN_ARRAY)) {
System.out.print("Marks [ ");
handleJsonArray(reader);
System.out.print("]");
} else if (token.equals(JsonToken.END_OBJECT)) {
reader.endObject();
return;
} else {
if (token.equals(JsonToken.NAME)) {
//get the current token
fieldname = reader.nextName();
}
if ("name".equals(fieldname)) {
//move to next token
token = reader.peek();
System.out.println("Name: "+reader.nextString() );
}
if("age".equals(fieldname)) {
//move to next token
token = reader.peek();
System.out.println("Age:" + reader.nextInt());
}
if("verified".equals(fieldname)) {
//move to next token
token = reader.peek();
System.out.println("Verified:" + reader.nextBoolean());
}
}
}
}
Output
Name: Mahesh Kumar
Age:21
Verified:false
Marks [ 100 90 85 100 14 95 ]
Your JSON has one tricky element - label arrays contain one-element JSON object. We can unwrap it using custom deserialiser. To do that let's create simple POJO structure which fit's JSON payload. JSON starts from [ so it means we need to parse it as an array. All elements have the same structure. We can define it like below:
class Phrase {
private String label;
private String domain;
#JsonAdapter(StringWrapperJsonDeserializer.class)
#SerializedName("synonymlabels")
private List<String> synonymLabels;
#JsonAdapter(StringWrapperJsonDeserializer.class)
#SerializedName("childrenlabels")
private List<String> childrenLabels;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public List<String> getSynonymLabels() {
return synonymLabels;
}
public void setSynonymLabels(List<String> synonymLabels) {
this.synonymLabels = synonymLabels;
}
public List<String> getChildrenLabels() {
return childrenLabels;
}
public void setChildrenLabels(List<String> childrenLabels) {
this.childrenLabels = childrenLabels;
}
#Override
public String toString() {
return "Phrase{" +
"label='" + label + '\'' +
", domain='" + domain + '\'' +
", synonymLabels=" + synonymLabels +
", childrenLabels=" + childrenLabels +
'}';
}
}
When we want to use another name for property in Java comparing to what we have in JSON we use SerializedName annotation. To inform Gson library that we would like to handle given element in a specific way we use JsonAdapter annotation. In case we do not know how to write custom deserialiser it is always safe to use Map<String, Object> type for unknown or random JSON object. In case we have list of objects we can use List<Map<String, Object>>. Let's write simple deserialiser for labels arrays:
class StringWrapperJsonDeserializer implements JsonDeserializer<List<String>> {
#Override
public List<String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonArray()) {
final JsonArray array = (JsonArray) json;
final int size = array.size();
if (size == 0) {
return Collections.emptyList();
}
List<String> labels = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
JsonObject jsonElement = (JsonObject) array.get(i);
Set<String> keys = jsonElement.keySet();
for (String key : keys) {
labels.add(jsonElement.getAsJsonPrimitive(key).getAsString());
}
}
return labels;
}
return Collections.emptyList();
}
}
Algorithm is quite simple: if given element is an array, iterate over it and take each object one-by-one. For each object get all keys and add corresponding values to labels list which is our result of deserialisation process. Example usage, could look like this:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
public class GsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
Phrase[] phrases = gson.fromJson(new FileReader(jsonFile), Phrase[].class);
Stream.of(phrases).forEach(System.out::println);
}
}
Above code prints:
Phrase{label='Hospital', domain='Health_Care', synonymLabels=[SHCO, HCO], childrenLabels=[Childern_Hospital, Mental_Hospital, Heart_Hospital, Orthopadic_Hospital, General_Hospital, Gynac_Hospital, Cancer_Hospital, Burn_Hospital, Trauma_Care_Hospital]}
Phrase{label='Doctor', domain='Health_Care', synonymLabels=[Clinician, Physician, Medical_Practitioner], childrenLabels=[Cardiaologist, Allergist, Nurologist, Gynacologist, General_Physician, Anesthetist, Physiotherapist, Urologist, Oncologist, Homeopath, Dentist]}
Read also:
JsonAdapter
Serializing and Deserializing a List with Gson

convert JSON from ajax request to JSON object in java

This is the form data
selectedDtlId: [{"id":"3","isReviewed":true,"notes":"notes asdf test add 2"},{"id":"2","isReviewed":true,"notes":""},{"id":"1","isReviewed":true,"notes":""}]
isReviewedAll: true
notesAll:
Upon running the below code in the Controller
Gson gson = new Gson();
gson.toJson(request.getParameter("selectedDtlId"));
response
"[{\"id\":\"3\",\"isReviewed\":true,\"notes\":\"notes asdf test add 2\"},{\"id\":\"2\",\"isReviewed\":true,\"notes\":\"\"},{\"id\":\"1\",\"isReviewed\":true,\"notes\":\"\"}]"
Expected resoponse
[
{
"id": "3",
"isReviewed": true,
"notes": "notes asdf test add 2"
},
{
"id": "2",
"isReviewed": true,
"notes": ""
},
{
"id": "1",
"isReviewed": true,
"notes": ""
}
]
You're calling toJson when you should be calling fromJson:
gson.fromJson(request.getParameter("selectedDtlId"), JsonElement.class);
Or if you have a model:
gson.fromJson(request.getParameter("selectedDtlId"), MyModel.class);
You should map it to a Class. (Also you are calling toJson when you should call fromJson)
Main
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
String jsonInString = "[{\"id\":\"3\",\"isReviewed\":true,\"notes\":\"notes asdf test add 2\"},{\"id\":\"2\",\"isReviewed\":true,\"notes\":\"\"},{\"id\":\"1\",\"isReviewed\":true,\"notes\":\"\"}]";
Gson gson = new Gson();
SelectedDtlId[] selectedDtlIds = gson.fromJson(jsonInString, SelectedDtlId[].class);
for (SelectedDtlId selectedDtlId : selectedDtlIds) {
System.out.println("id: " + selectedDtlId.getId());
System.out.println("notes: " + selectedDtlId.getNotes());
System.out.println("isReviewed: " + selectedDtlId.isReviewed());
}
}
}
Model
import com.google.gson.annotations.SerializedName;
public class SelectedDtlId {
#SerializedName("id")
private int id;
#SerializedName("isReviewed")
private boolean isReviewed;
#SerializedName("notes")
private String notes;
// getters & setters
}
the result should be:
id: 3
notes: notes asdf test add 2
isReviewed: true
id: 2
notes:
isReviewed: true
id: 1
notes:
isReviewed: true

Spring RestTemplate parse JSON object with variable keyname

I have a REST API call that returns the following JSON object. I need to parse this with Spring's RestTemplate. The problem is that the first key ISBN:0132856204 is variable (the numbers change depending on the book). How would I go about doing this?
{
"ISBN:0132856204": {
"publishers": [
{
"name": "Pearson"
}
],
"pagination": "xxiv, 862p",
"identifiers": {
"isbn_13": [
"978-0-13-285620-1"
],
"openlibrary": [
"OL25617855M"
]
},
"weight": "1340 grams",
"title": "Computer networking",
"url": "https://openlibrary.org/books/OL25617855M/Computer_networking",
"number_of_pages": 862,
"cover": {
"small": "https://covers.openlibrary.org/b/id/7290810-S.jpg",
"large": "https://covers.openlibrary.org/b/id/7290810-L.jpg",
"medium": "https://covers.openlibrary.org/b/id/7290810-M.jpg"
},
"publish_date": "2013",
"key": "/books/OL25617855M",
"authors": [
{
"url": "https://openlibrary.org/authors/OL31244A/James_F._Kurose",
"name": "James F. Kurose"
},
{
"url": "https://openlibrary.org/authors/OL658909A/Keith_W._Ross",
"name": "Keith W. Ross"
}
],
"subtitle": "A Top-Down Approach"
}
}
In here "ISBN:0132856204" is a value and also a key for your business.
To get ISBN first, what about wrapping json content with 1 more closure?
{
"yourAwesomePlaceHolderKey" :
{
"ISBN:0132856204": {
......
}
}
}
First get the ISBN key as a value, then your ISBN value can be used as a key to get related content.
First goal will be extracting -String1,Object1- pair where String1 is "yourAwesomePlaceholderKey" and second goal will be again extracting -String2,Object2- from Object1 where String2 is your ISBN key.
This is the way I solved it, using JsonPath for getting the book out of the JSON object and Jackson for mapping it to a Book object:
RestTemplate restTemplate = new RestTemplate();
String isbn = "0132856204";
String endpoint = "https://openlibrary.org/api/books?jscmd=data&format=json&bibkeys=ISBN:{isbn}";
//Get JSON as String
String jsonString = restTemplate.getForObject(endpoint, String.class, isbn);
//Configure JsonPath to use Jackson for mapping
Configuration.setDefaults(new Configuration.Defaults() {
private final JsonProvider jsonProvider = new JacksonJsonProvider();
private final MappingProvider mappingProvider = new JacksonMappingProvider();
#Override
public JsonProvider jsonProvider() {
return jsonProvider;
}
#Override
public MappingProvider mappingProvider() {
return mappingProvider;
}
#Override
public Set<Option> options() {
return EnumSet.noneOf(Option.class);
}
});
//Parse the JSON as a book
Book book = JsonPath.parse(jsonString).read("$.ISBN:" + isbn, Book.class);
You can use JsonProperty to solve
#JsonProperty("ISBN:0132856204")

Categories