How to submit a JSON object with headers - java

I mount a list of objects and need to turn this list into a JSON, but with headers.
I'm doing it in this way:
public String convertToJson(List personDto) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(personDto);
return jsonInString;
I do not know how to insert headers that should have some information, like: date / time, access key etc...
For information to be placed in the header!
Then I have to send a POST with Spring Boot containing this JSON object.
My JSON has to leave like this:
{
"table": "person",
"rows":
[
{
"PersonID": 1,
"name": "Name o person",
"RM": "56656565",
"RG": "8787845-7",
},
{
"PersonID": 2,
"name": "Name o person",
"RM": "56656565",
"RG": "8787845-7"
}
]
}
My DTO class:
public class PersonDto {
private Integer lNum;
private String sName;
private String sRg;
private String sRm;
public String getsRm() {
return sRm;
}
public void setsRm(String sRm) {
this.sRm = sRm;
}
public Integer getlNum() {
return lNum;
}
public void setlNum(Integer lNum) {
this.lNum = lNum;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
public String getsRg() {
return sRg;
}
public void setsRm(String sRm) {
this.sRm= sRm;
}
}

You can use the jersey client for this. It integrates well with Spring
Following the is minimum stuff you need to do to hit an endpoint of an active application along with request headers
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target("http://localhost:7777/someApp/");
Response response = webTarget.request().header("key", "value").put(Entity.json(jsonInString), EXPECTED_POJO.class)

Related

Get the value of items of a Json with Java Spring Boot

I'm trying to extract API data from the Json file below.
I want to retrieve the "name" of each "item".
Once the "name" is retrieved, I want to create a new Json that will contain :
{name: "toto", name: "titi"....}
The goal is then to create an API on my side which on a call from http://localhost/getitems will return the result of the Json created.
I'm new to Java and Spring Boot, so if you think there is a code that is easier, let me know, i hope you can help me to create that new Json file easily. Thanks !
// Json File (it has been reduced, more than 700 name are present)
{
"kind": "Space",
"apiVersion": "v1",
"metadata": {
"selfLink": "something",
"resourceVersion": "something"
},
"items": [
{
"metadata": {
"name": "projet1"
}
},
{
"metadata": {
"name": "com-cicd"
}
}
]
}
// TestGet.java Class
public static NameSpaceJson getPostWithCustomHeaders(String DebutUrl, String MilieuUrl, String ParamUrl) {
String url = DebutUrl.concat(MilieuUrl).concat(ParamUrl);
String Bearer = "...";
// create headers & template
HttpHeaders headers = new HttpHeaders();
RestTemplate restTemplate = new RestTemplate();
// set `accept` header for the type of response
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// set custom header, bearer here too
headers.set("x-request-source", "desktop");
headers.set("Authorization", "Bearer "+Bearer);
// build the request
#SuppressWarnings({ "rawtypes", "unchecked" })
HttpEntity request = new HttpEntity(headers);
// use `exchange` method for HTTP call, this one permits us to use bearer for auth
ResponseEntity<NameSpaceJson> response = restTemplate.exchange(url, HttpMethod.GET, request, NameSpaceJson.class, 1);
if(response.getStatusCode() == HttpStatus.OK) {
return response.getBody();
} else {
return null;
}
}
// The name in the same file
public static void main(String[] args) {
TestGet.disableSSLCertificateChecking();
NameSpaceJson resultresponse = getPostWithCustomHeaders("https...","api","names");
// Long response = resultresponse.getValue().getId();
List<Item> response = resultresponse.getItems();
String test = GenerateNewJsonNameSpace.createJsonContent(response);
System.out.println(test);
}
//NameSpaceJson.java File
package com.example.consumingrest;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class NameSpaceJson {
private String kind;
private String apiVersion;
private List<Item> items;
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getApiVersion() {
return apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
//Metadata.java
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Metadata {
private String name;
private String creationTimestamp;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCreationTimestamp() {
return creationTimestamp;
}
public void setCreationTimestamp(String creationTimestamp) {
this.creationTimestamp = creationTimestamp;
}
}
//Item.java
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Item {
Metadata metadata;
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
}
// GenerateNewJsonNameSpace ( this is what i have tried.. but i'm sure we can do really better.. )
package com.example.consumingrest;
import java.util.List;
public class GenerateNewJsonNameSpace {
public static String createJsonContent(List<Item> ListOfNameSpace) {
if(ListOfNameSpace.isEmpty()) {
return null;
}else {
String LeJson;
LeJson = "{";
for(int i = 0; i < ListOfNameSpace.size(); i++) {
LeJson.concat(ListOfNameSpace.get(i).getMetadata().getName());
LeJson.concat(", \n");
}
LeJson.concat("}");
return LeJson;
}
}
}
you can use a library named Gson, which is created by google specifically for handling the JSON data.
All you need to do is create a new Gson object and parse the JSON with it.
You can do in just couple of lines
String jsonString = "{ \"kind\": \"Space\", \"apiVersion\": \"v1\", \"metadata\": { \"selfLink\": \"something\", \"resourceVersion\": \"something\" }, \"items\": [ { \"metadata\": { \"name\": \"projet1\" } }, { \"metadata\": { \"name\": \"affeccom-cicd\" } } ] }";
JsonObject data = new Gson().fromJson(jsonString, JsonObject.class);
JsonArray names = data .get("items").getAsJsonArray();
for(JsonElement element : names){
JsonObject object = element.getAsJsonObject();
System.out.println(object.get("metadata").getAsJsonObject().get("name").getAsString());
}

Cannot deserialize instance of `org.json.JSONObject`

I have a basic SpringBoot 2.1.5.RELEASE app. Using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file with some RestControllers.
In 1 of the controller this is the body I send:
{
"depositHotel": "xxx",
"destinationHotel": "aaa",
"depositHotelAmount": "0.2",
"destinationHotelAmount": "4",
"destinationAddress": [{
"address": "asdf",
"tag": ""
}],
"refundAddress": [{
"address": "pio",
"tag": ""
}]
}
so I create this class to use it as a RequestBody:
public class HotelswitchHotelOrderRequestBody {
public static class Builder {
private String depositHotel;
private String destinationHotel;
private Float depositHotelAmount;
private Float destinationHotelAmount;
private JSONObject destinationAddress;
private JSONObject refundAddress;
public Builder(String depositHotel, String destinationHotel) {
this.depositHotel = depositHotel;
this.destinationHotel = destinationHotel;
}
public Builder withDepositHotelAmount (Float depositHotelAmount) {
this.depositHotelAmount = depositHotelAmount;
return this;
}
public Builder withDestinationHotelAmount (Float destinationHotelAmount) {
this.destinationHotelAmount = destinationHotelAmount;
return this;
}
public Builder toDestinationAddress (JSONObject destinationAddress) {
this.destinationAddress = destinationAddress;
return this;
}
public Builder toRefundAddress (JSONObject refundAddress) {
this.refundAddress = refundAddress;
return this;
}
public HotelswitchHotelOrderRequestBody build(){
HotelswitchHotelOrderRequestBody order = new HotelswitchHotelOrderRequestBody();
order.depositHotel = this.depositHotel;
order.depositHotelAmount = this.depositHotelAmount;
order.destinationAddress = this.destinationAddress;
order.destinationHotel = this.destinationHotel;
order.destinationHotelAmount = this.destinationHotelAmount;
order.refundAddress = this.refundAddress;
return order;
}
}
private String depositHotel;
private String destinationHotel;
private Float depositHotelAmount;
private Float destinationHotelAmount;
private JSONObject destinationAddress;
private JSONObject refundAddress;
private HotelswitchHotelOrderRequestBody () {
//Constructor is now private.
}
public String getDepositHotel() {
return depositHotel;
}
public void setDepositHotel(String depositHotel) {
this.depositHotel = depositHotel;
}
public String getDestinationHotel() {
return destinationHotel;
}
public void setDestinationHotel(String destinationHotel) {
this.destinationHotel = destinationHotel;
}
public Float getDepositHotelAmount() {
return depositHotelAmount;
}
public void setDepositHotelAmount(Float depositHotelAmount) {
this.depositHotelAmount = depositHotelAmount;
}
public Float getDestinationHotelAmount() {
return destinationHotelAmount;
}
public void setDestinationHotelAmount(Float destinationHotelAmount) {
this.destinationHotelAmount = destinationHotelAmount;
}
public JSONObject getDestinationAddress() {
return destinationAddress;
}
public void setDestinationAddress(JSONObject destinationAddress) {
this.destinationAddress = destinationAddress;
}
public JSONObject getRefundAddress() {
return refundAddress;
}
public void setRefundAddress(JSONObject refundAddress) {
this.refundAddress = refundAddress;
}
}
But I have this error when receiving the object:
JSON parse error: out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `org.json.JSONObject` out of START_ARRAY token
JSONObject's representation in actual JSON is a hash i.e. {...}. In your json data you're providing an array of hashes [{...}] which is not the same. Judging from your domain I don't think it has to be multiple values, so you can just omit [] in your payload and if it does then the fields in your Java class can be defined as JSONArray.
However, I think you should go with defining an Address class and either using
private Address destinationAddress;
private Address refundAddress;
or if it indeed does have to be an object array
private List<Address> destinationAddresses;
private List<Address> refundAddresses;
I had a similar usecase , where I could not define the json to a POJO. Using com.fasterxml.jackson.databind.JsonNode instead of the JSONObject worked.

How to map A JSON single item from a list<int, String) to String with Jackson?

In some incoming JSON there is a list
"age" : 27,
"country", USA,
"fields": [
{
"id": 261762251,
"value": "Fred"
},
{
"id": 261516162,
"value": "Dave"
},
]
I know the key int for what I am looking for [261762251].
I would like to map that to a plain String field firstname in the User object with the rest of the bottom level fields from the JSON. I have tried extending com.fasterxml.jackson.databind.util.StdConverter and adding the annotation #JsonSerialize(converter=MyConverterClass.class) to the variable in the User class with no luck.
My architecture is like this:
public class User {
private String age;
private String country;
private String firstname; // this is the field in the list that needs converting
// getters and setters
}
public class ApiClient{
public User getUsers(){
Response response;
//some code to call a service
return response.readEntity(User.class)
}
}
What is the best approach to achieve this?
You can try something like below:
class Tester
{
public static void main(String[] args) throws Exception {
String s1 = "{\"fields\": [ { \"id\": 261762251, \"value\": \"Fred\" }, { \"id\": 261516162, \"value\": \"Dave\" }]}";
ObjectMapper om = new ObjectMapper();
Myclass mine = om.readValue(s1, Myclass.class);
System.out.println(mine);
}
}
public class User {
private String age;
private String country;
private String firstname; // this is the field in the list that needs converting
#JsonProperty("fields")
private void unpackNested(List<Map<String,Object>> fields) {
for(Map<String,Object> el: fields) {
if((Integer)el.get("id") == 261762251) {
firstname = el.toString();
}
}
}
// getters and setters
}

json to java Object using jackson

Hi i want to convert this json to json object in java so that i can pass it to http request to call an api
{
"aliasNaming": true,
"dataServiceType": "BROWSE",
"deviceName": "MyDevice",
"langPref": " ",
"maxPageSize": "2000",
"outputType": "VERSION1",
"password": "!jshjhsdhshdj",
"query": {
"autoClear": true,
"autoFind": true,
"condition": [
{
"controlId": "F4211.CO",
"operator": "EQUAL",
"value": [
{
"content": "00098",
"specialValueId": "LITERAL"
}
]
},
{
"controlId": "F4211.DCTO",
"operator": "EQUAL",
"value": [
{
"content": "SM",
"specialValueId": "LITERAL"
}
]
},
{
"controlId": "F4211.UPMJ",
"operator": "GREATER_EQUAL",
"value": [
{
"content": "01/01/17",
"specialValueId": "LITERAL"
}
]
}
],
"matchType": "MATCH_ALL"
},
"returnControlIDs": "F4211.DOCO|F4211.TRDJ|F4211.CRCD|F4211.AN8|F4211.DSC2|F4211.DSC1|F4211.LITM|F4211.LOTN|F4211.UORG|F4211.UPRC|F4211.AEXP",
"targetName": "F4211",
"targetType": "table",
"token": "044biPNadxNVGhyAKdrImoniK98OOa2l86ZA63qCr4gE5o=MDIwMDA4LTIyNDU5MjUxMTY2MzY3NTA3MTRNeURldmljZTE1Mzc0MjYwMjAyNTk=",
"username": "Ali"
}
i have created 4 models using http://www.jsonschema2pojo.org.
those models just have getter setter in it. look something like this
#JsonProperty("aliasNaming")
private Boolean aliasNaming;
#JsonProperty("dataServiceType")
private String dataServiceType;
#JsonProperty("deviceName")
private String deviceName;
#JsonProperty("langPref")
private String langPref;
#JsonProperty("maxPageSize")
private String maxPageSize;
#JsonProperty("outputType")
private String outputType;
#JsonProperty("password")
private String password;
#JsonProperty("query")
private Query query;
#JsonProperty("returnControlIDs")
private String returnControlIDs;
#JsonProperty("targetName")
private String targetName;
#JsonProperty("targetType")
private String targetType;
#JsonProperty("token")
private String token;
#JsonProperty("username")
private String username;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("aliasNaming")
public Boolean getAliasNaming() {
return aliasNaming;
}
#JsonProperty("aliasNaming")
public void setAliasNaming(Boolean aliasNaming) {
this.aliasNaming = aliasNaming;
}
#JsonProperty("dataServiceType")
public String getDataServiceType() {
return dataServiceType;
}
#JsonProperty("dataServiceType")
public void setDataServiceType(String dataServiceType) {
this.dataServiceType = dataServiceType;
}
#JsonProperty("deviceName")
public String getDeviceName() {
return deviceName;
}
#JsonProperty("deviceName")
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
#JsonProperty("langPref")
public String getLangPref() {
return langPref;
}
#JsonProperty("langPref")
public void setLangPref(String langPref) {
this.langPref = langPref;
}
#JsonProperty("maxPageSize")
public String getMaxPageSize() {
return maxPageSize;
}
#JsonProperty("maxPageSize")
public void setMaxPageSize(String maxPageSize) {
this.maxPageSize = maxPageSize;
}
#JsonProperty("outputType")
public String getOutputType() {
return outputType;
}
#JsonProperty("outputType")
public void setOutputType(String outputType) {
this.outputType = outputType;
}
#JsonProperty("password")
public String getPassword() {
return password;
}
#JsonProperty("password")
public void setPassword(String password) {
this.password = password;
}
#JsonProperty("query")
public Query getQuery() {
return query;
}
#JsonProperty("query")
public void setQuery(Query query) {
this.query = query;
}
#JsonProperty("returnControlIDs")
public String getReturnControlIDs() {
return returnControlIDs;
}
#JsonProperty("returnControlIDs")
public void setReturnControlIDs(String returnControlIDs) {
this.returnControlIDs = returnControlIDs;
}
#JsonProperty("targetName")
public String getTargetName() {
return targetName;
}
#JsonProperty("targetName")
public void setTargetName(String targetName) {
this.targetName = targetName;
}
#JsonProperty("targetType")
public String getTargetType() {
return targetType;
}
#JsonProperty("targetType")
public void setTargetType(String targetType) {
this.targetType = targetType;
}
#JsonProperty("token")
public String getToken() {
return token;
}
#JsonProperty("token")
public void setToken(String token) {
this.token = token;
}
#JsonProperty("username")
public String getUsername() {
return username;
}
#JsonProperty("username")
public void setUsername(String username) {
this.username = username;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
Now i want to set the values in these models by creating their respective objects and finally i got one main object with all the data. like this
Value Vobj1 = new Value();
Vobj1.setContent("00098");
Vobj1.setSpecialValueId("LITERAL");
List<Value> valueList1= new ArrayList<Value>();
valueList1.add(Vobj1);
Value Vobj2 = new Value();
Vobj2.setContent("SM");
Vobj2.setSpecialValueId("LITERAL");
List<Value> valueList2= new ArrayList<Value>();
valueList2.add(Vobj2);
Value Vobj3 = new Value();
Vobj3.setContent("01/01/17");
Vobj3.setSpecialValueId("LITERAL");
List<Value> valueList3= new ArrayList<Value>();
valueList3.add(Vobj3);
Condition Cobj1 = new Condition();
Cobj1.setControlId("F4211.CO");
Cobj1.setOperator("EQUAL");
Cobj1.setValue(valueList1);
Condition Cobj2 = new Condition();
Cobj2.setControlId("F4211.DCTO");
Cobj2.setOperator("EQUAL");
Cobj2.setValue(valueList1);
Condition Cobj3 = new Condition();
Cobj3.setControlId("F4211.UPMJ");
Cobj3.setOperator("GREATER_EQUAL");
Cobj3.setValue(valueList1);
List<Condition> conditionList1 = new ArrayList<Condition>();
conditionList1.add(Cobj1);
conditionList1.add(Cobj2);
conditionList1.add(Cobj3);
Query Qobj1= new Query();
Qobj1.setAutoClear(true);
Qobj1.setAutoFind(true);
Qobj1.setCondition(conditionList1);
Qobj1.setMatchType("MATCH_ALL");
JSONStructure obj=new JSONStructure();
obj.setAliasNaming(true);
obj.setDataServiceType("BROWSE");
obj.setDeviceName("MyDevice");
obj.setLangPref(" ");
obj.setMaxPageSize("2000");
obj.setOutputType("VERSION1");
obj.setPassword("!J0g3t6000");
obj.setQuery(Qobj1);
obj.setReturnControlIDs("F4211.DOCO|F4211.TRDJ|F4211.CRCD|F4211.AN8|F4211.DSC2|F4211.DSC1|F4211.LITM|F4211.LOTN|F4211.UORG|F4211.UPRC|F4211.AEXP");
obj.setTargetName("F4211");
obj.setTargetType("table");
obj.setToken(Token);
obj.setUsername("JOGET");
Now obj is my final object that i am going to pass to an http request and call the api and get the data from it. i want to make sure that my json is created correct, how am i suppose to print the all the data inside this object? and am i going correct with this approach?
if you use maven put gson into your pom.xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
then print your object like this
System.out.println(new Gson().toJson(yourObj));
your object will print in json
I found two full working examples that is familiar with your case.
1) Using Gson refer to the tutorial Parse json string and java object into Gson tree model
2) Using Jackson refer to the tutorial Convert Java Object to/from JSON using JACKSON API
Hope this help.

Send json using jackson and spring boot

I need to send a json to a web address where this json will be consumed, basically I have a list of Dto's that I need to turn into a Json (with jackson).
Some information must be passed in the header:
timestamp= time, key= blablabla, accesskey= bla bla bla
As I have no experience with spring, i need to know how to do the HTTP request using Spring boot
(is it a post?)
Here's what I've implemented so far:
Student Dto Class
public class StudentDto {
private String name;
private String RM;
private String RG;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRM() {
return RM;
}
public void setRM(String RM) {
this.RM = RM;
}
public String getRG() {
return RG;
}
public void setRG(String RG) {
this.RG = RG;
}
}
Turning my list of students into json
public String convertToJson(List obj) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
return jsonInString;
}
}
And this is the format json has to leave
{
"table": "student",
"rows":
[
{
"PersonID": 1,
"name": "Name",
"RM": "56656565",
"RG": "8787845-7",
},
{
"PersonID": 2,
"name": "Name",
"RM": "56656565",
"RG": "8787845-7"
}
]
}
below is and example of how to use rest template. You'll want to create a class for the request that has String table; and List<StudentDto> rows; as members
private static void createEmployee()
{
final String uri = "http://localhost:8080/springrestexample/employees";
MultiValueMap<String> headers = new MultiValueMap<>();
//set headers
HttpEntity<EmployeeVO> newEmployee = new HttpEntity<>(new EmployeeVO(-1, "Adam", "Gilly", "test#email.com"),headers);
RestTemplate restTemplate = new RestTemplate();
EmployeeVO result = restTemplate.postForObject( uri, newEmployee, EmployeeVO.class);
System.out.println(result);
}
*edit added headers
*edid look here for json formatting
you will also need to have the id field added to your object

Categories