Passing json as a String - java

For a Json body like
{
"firstName": "hello",
"lastName": "abc"
}
I am writing as
JSONObject body = new JSONObject();
body.put("firstName", "hello");
body.put("lastName", "abc");
and then converting body to string to pass it as string parameter
How can I write the same for body with response like
{
"class": {
"firstName": "hello",
"lastName": "abc"
}
}
I need to convert json to string afterwards

I think this should do the trick
JSONObject innerBody = new JSONObject();
innerBody.put("firstName", "hello");
innerBody.put("lastName", "abc");
JSONObject outerBody = new JSONObject();
outerBody.put("class",innerBody);

Create a class:
public class DataSource {
private String firstName;
private String lastName;
//Constructor, getter, setter
}
And then:
JSONObject body = new JSONObject();
DataSource data = new DataSource();
data.setFirstName("bla");
data.setLastName("bla bla");
body.put("class", data );

Related

Java object attribute not showing in API Json response with Spring Boot Jackson

I have a java dto model class which has some attributes. When in the API Controller class I am trying to convert the java object to json with objectMapper.readValue(..) it is not converting one field (_atType) and that is why in response body I am not able to see #type json key data.
Model / Dto class:
#JsonInclude(JsonInclude.Include.NON_EMPTY)
#JsonIgnoreProperties(ignoreUnknown = true)
#Schema(description = "Abc...")
public class SomeDto {
#JsonProperty("id")
private String id = null;
#JsonProperty("description")
private String description = null;
#JsonProperty("state")
private TaskStateType state = null;
#JsonProperty("#type")
private String _atType = null;
public CheckServiceQualification _atType(String _atType) {
this._atType = _atType;
return this;
}
public String getAtType() {
return _atType;
}
public void setAtType(String _atType) {
this._atType = _atType;
}
.... other getter setters for other attributes
}
Response json coming as:
{
"id": "55",
"description": "Query Service Qualification POST Illustration",
"state": "accepted"
}
Response json expected like below:
{
"id": "55",
"description": "Query Service Qualification POST Illustration",
"state": "accepted",
"#type": "Type1"
}
API Controller method :
public ResponseEntity<SomeDto> createQualification(#Parameter(in = ParameterIn.DEFAULT, description = "The QueryServiceQualification to be created", required = true, schema = #Schema()) #Valid #RequestBody QueryServiceQualificationCreate body) {
logger.info("Received create QueryServiceQualification request.");
String responseJson = "{ \"id\": \"55\", \"description\": \"Query Service Qualification POST Illustration\", \"state\": \"accepted\", \"_atType\": \"Type1\"}";
SomeDto someDto = null;
try {
someDto = objectMapper.readValue(responseJson, SomeDto.class);
return ResponseEntity.status(HttpStatus.CREATED).body(someDto);
} catch (JsonProcessingException e) {
logger.error("Could not able to convert json string to object", e);
}
return new ResponseEntity<SomeDto>(HttpStatus.NOT_IMPLEMENTED);
}
So though responseJson variable in the API Controller method (above one) has "_atType": "Type1" but still in API json response in Postman I am not able to see the attribute "#type": "Type1" . Pleas help.
Within the example you provided, the field name is provided as "_atType" in json:
"_atType" : "Type1"
However, it is specified as "#type" on model object:
#JsonProperty("#type")
private String _atType = null;
You will need to have "#type" field in json data or remove this part on model object: #JsonProperty("#type")

Problems with JSONObject vs JSONArray in Android

I have a pretty specific problem I guess. I'm using Volley library to get a String response from URL, the response is following:
{"email":"imribar#gmail.com","phone":"7(707)111-11-11","family_name":"Жилин","name":"Иван","role":0}
I get this response by converting my SQL query array to JSON in PHP
$output=$db->query("SELECT email, phone, family_name, name, role FROM users WHERE email=?", "$email")->fetchArray();
$json=json_encode($output, JSON_UNESCAPED_UNICODE);
echo"$json";
What I need to do next is go throught this JSON and insert records to local database in my Android APP. In order to do that, I do following:
if(response.contains("email")) {
testResponse.setText("Response is2: " + response);
try {
JSONArray jsonArr = new JSONArray(response);
for(int i=0; i < jsonArr.length();i++){
JSONObject jsonObj = jsonArr.getJSONObject(i);
Log.i("User",jsonObj.toString());
User user = new User();
user.email= jsonObj.getString("email");
user.phone=jsonObj.getString("phone");
user.firstName=jsonObj.getString("name");
user.lastName=jsonObj.getString("family_name");
user.role=jsonObj.getInt("role");
user.token="123123123fsadf";
insertUser inewuser = new insertUser();
inewuser.execute(user);
}
} catch (JSONException e) {
Log.i("JSONerror", e.toString());
}
}
I keep getting the following error:
13:24:59.518 22389-22389/com.local.school I/JSONerror: org.json.JSONException: Value {"email":"imribar#gmail.com","phone":"7(707)111-11-11","family_name":"Жилин","name":"Иван","role":0} of type org.json.JSONObject cannot be converted to JSONArray
Any idea what I can do on PHP side to change the JSONString (add [], or add a name to an array), or what do I need to do in Android?
Your response does not have a json array, only an object. 
Array is something like this. 
[{
"email": "imribar1#gmail.com",
"phone": "7(707)990-77-72",
"family_name": "Жилин2",
"name": "Иван2",
"role": 2
},
{
"email": "imribar#gmail.com",
"phone": "7(707)990-77-71",
"family_name": "Жилин",
"name": "Иван",
"role": 0
}
]
So remove the  loop and try. 
if(response.contains("email")) {
testResponse.setText("Response is2: " + response);
try {
JSONObject jsonObj = jsonArr.getJSONObject(i);
Log.i("User",jsonObj.toString());
User user = new User();
user.email= jsonObj.getString("email");
user.phone=jsonObj.getString("phone");
user.firstName=jsonObj.getString("name");
user.lastName=jsonObj.getString("family_name");
user.role=jsonObj.getInt("role");
user.token="123123123fsadf";
insertUser inewuser = new insertUser();
inewuser.execute(user);
} catch (JSONException e) {
Log.i("JSONerror", e.toString());
}
}
I suggest you use a JsonObjectRequest instead of StringRequest when you call Volley in your app. It is almost the same as StringRequest but it gets a JSONObject as an answer.
String url = "http://my-json-feed";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// your cose goes here:
JSONObject jsonObject = new JSONObject(response.toString());
User user = new User();
user.email= jsonObject.getString("email");
user.phone=jsonObject.getString("phone");
user.firstName=jsonObject.getString("name");
user.lastName=jsonObject.getString("family_name");
user.role=jsonObject.getInt("role");
user.token="123123123fsadf";
insertUser inewuser = new insertUser();
inewuser.execute(user);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
jsonObjectRequest
Your json string has a json object as root object, while in code you are using JSONArray jsonArr = new JSONArray(response); to parse it as if it were an array. Assuming your used json library, you would have to start parsing the json using:
JSONObject jsonObj = new JSONObject(response);
The alternative would be to actually generate a json array ([...]) rather than a json object ({...}) so that your parsing code will recognise it. The choice you want to make will depend on whether you always send a single json object or whether you want to be able to send multiple json objects (in a json array).

How to get data from service and database and send post data to server?

I'm using RestTemplate JSON to get data from service and database, and then send POST to server. I have tested on Postmen and it get result 200
My format json:
{
"senderUser": "myemail#gmail.com",
"data": [
{
"actionType": "update-contact",
"data": {
"name": "NakiTa ",
"lastname": "Isumi",
"type": 0,
"title": "ms",
"passport": "123123",
"gender": 1,
"dateOfBirth": "03-01-2021",
"emails": [
{
"value": "test#gmail.com"
}
],
"phones": [
{
"value": "0902032618"
}
],
"addresses": [
{
"addressDetail": "Osaka",
"street": "Osaka",
"city": "Osaka",
"state": "JP",
"country": {
"code": "jp",
"name": "Japan"
}
}
],
"cusFields": [
{
"600f9cb0f02f084bd8a3dcdb": "TEST"
}
],
"customerType": "company"
}
}
]
}
My class:
#RequestMapping(value = "/getAllCustomerBasic.do", method = RequestMethod.GET)
public ResponseEntity<List<MyClassMap>> getAllCustomerBasic(#RequestParam Map<String, Object> params,
HttpServletRequest request) throws Exception {
LOGGER.debug("groupCode : {}", params.get("custId"));
RestTemplate restTemplate = new RestTemplate();
MappingJackson2HttpMessageConverter jsonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
jsonHttpMessageConverter.getObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
restTemplate.getMessageConverters().add(jsonHttpMessageConverter);
String url = "https://myservice/6670011cbd4a674458d3b26025/90336429462601e7f3326641898fabd9948b349d";
List<MyClassMap> customerList = customerService.getAllCustomerViewBasicInfo(params); // .selectAccBank(params);
try {
JSONArray arrayParent = new JSONArray();
for(int i=0 ; i<customerList.size() ; i++) {
arrayParent.put(customerList.get(i));
}
JSONObject objectParent = new JSONObject();
objectParent.put("data", arrayParent);
JSONObject objectChild = new JSONObject();
objectChild.put("senderUser", "myemail#gmail.com");
JSONObject objectChildData = new JSONObject();
objectChildData.put("actionType", "update-contact");
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());
HttpEntity<String> entity = new HttpEntity<String>(objectParent.toString(), headers);
String result = restTemplate.postForObject(url, entity, String.class);
LOGGER.info(result);
LOGGER.info("header: " + entity.getHeaders());
LOGGER.info("body" + entity.getBody());
}
catch (HttpClientErrorException exception) {
// TODO Auto-generated catch block
exception.printStackTrace();
}
return ResponseEntity.ok(customerList); // customerList jSONObject
}
With customerService will get data from database success but I When I build and check data it seem happen an exception follow as:
body{"data":{}}
it seem get data is null and can not get all data. How to fix the problem ? many thank
RestTemplate makes the serialization to json automatically. You only have to define a Java Class with the same attributes (and with the same type) the API expects and in the postForObject method indicate that the object is the same as your class instead a String.class.
For example, if your MyClassMap data have the same attributes as the elements in the data json array, it could be:
//You have to add getters and setters and constructor
public Class Request {
private String senderUser;
private List<MyClassMap> data;
}
ClassRequest request= new ClassRequest();
request.setData(customerList);
request.setSenderUser("example");
HttpEntity<ClassRequest> entity = new HttpEntity<ClassRequest>(request, headers);
String result = restTemplate.postForObject(url, entity, ClassRequest.class);

How to convert a JsonObject object to a list of another object type

I have a service that will return a list of objects something like this:
{
"myobject": [
{
"first" : "10",
"second": 5.000
},
{
"first" : "20",
"second": 20.000
},
{
"first" : "30",
"second": 50.000
}
]
}
I take this object with this request
public String getMyObject() {
String url = UriComponentsBuilder.fromHttpUrl(myUrl);
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
return response.getBody();
}
I need to put this list inside a list of Objects of this type:
#Getter
#Setter
public class MyObject{
private String firstParam
private String secondParam
}
How to do this? Can anybody help me?
The main problem here is what you expect as a response object at this line:
ResponseEntity<myObject[]> response = restTemplate.getForEntity(url , myObject[].class);
Instead you should ask for a MyDTO object since also your controller is returning a MyDTO object:
ResponseEntity<MyDTO> response = restTemplate.getForEntity(url , MyDTO.class);
and retrieving the list with a
List<MyObject> myList = myDTO.getMyObject();
after extracting the MyDTO object from the ResponseEntity response object.

How to generate JSON Stringer in Android for this format

I need to send data to database in this format -
{"param1":"value1", "param2":"value2", "param3": {"username": "admin", "password": "123"}}
How to generate this using JSONStringer ?
I tried this -
vm = new JSONStringer().object().key("param1").value("value1")
.object().key("param2").value("value2")
.key("param3").object()
.key("username").value("admin")
.key("password").value("123")
.endObject().endObject().endObject();
But I'm getting this error -
org.json.JSONException: Nesting problem at
org.json.JSONStringer.beforeValue(JSONStringer.java:415)
JSONObject object1 = new JSONObject();
object1.put("param1", "value1");
object1.put("param2", "param2");
JSONObject innerObject1 = new JSONObject();
innerObject1.put("username", "admin");
innerObject1.put("password", "123");
object1.put("param3",innerObject1);
String jsonStr = object1.toString();
Ideally reverse of JSON parsing can be applied to create a json string object, so that the same can be send to Server/DB
Try this
try {
JSONObject object=new JSONObject();
object.put("param1","value1");
object.put("param2","value2");
JSONObject param3=new JSONObject();
paraam3.put("username","admin");
paraam3.put("password","123");
object.put("param3",param3);
} catch (JSONException e) {
e.printStackTrace();
}
You can create model which will be your java file same as your JSON file and can use gson library which is supported by Google to do JSON parsing. The library is quite flexible and easy to use then using traditional method of JSON parsing.
Model File
public class Response {
public String param1;
public String param2;
public Param3 param3;
public Response(String param1, String param2) {
this.param1 = param1;
this.param2 = param2;
}
public class Param3 {
public String username;
public String password;
public Param3(String username, String password) {
this.username = username;
this.password = password;
}
}
}
In file in which you insert data
Response res = new Response("value1", "value2", new Param3("admin","123"));
String dbResult = new Gson.toJson(res);
If you are looking for the actual solution using org.json.JSONStringer
JSONWriter writer = stringer3.object()
.key("param1").value("value1")
.key("param2").value("value2")
.key("param3").object()
.key("username").value("admin")
.key("password").value("123")
.endObject()
.endObject();
System.out.println(writer.toString());
You can think of the object() method as opening a new parenthesis and the endObject() as closing it

Categories