Java Objects to JSON, parse using javascript - java

I am trying to send an array of pojo's as a response to an ajax call.
Inside of my pojo, I have the following toString():
#Override
public String toString() {
return "Expense [period=" + period + ", description=" + description +
", category="+ category + ", subCategory="+subCategory+", "
+ "amount="+amount+", store="+store+"]";
}
Then, inside of my doGet method, I build up the arraylist of pojos, and am trying to write them out, using:
Gson gson = new Gson();
String json = gson.toJson(expensesForPeriod);
out.write(json);
Where expensesForPeriod is an arraylist of expense objects.
Is this the correct way to send an arraylist of json objects?
On the javascript side, how would I convert the json string to an array of objects, and iterate over them?

You should use #Expose before each of your instance members in the class definition, then call the Gson file on that instance.

For java side:
you shouldn't override toString method, just need to use Gson to parse object to json string
For javascript side:
you can follow this tutorial: link

Related

How to convert Json to Java for making POST request using rest assured

I would like to post below request using the below payload and looking for a better way to do this rather than posting it this way with escaping characters.
"{\n" + "\t\"name\": \"nameValue\",\n" + "\t\"age\": \"ageValue\",\n" + "\t\"sex\": \"sexValue\",\n" + "\t\"mobile\": \"mobileVal-uk\",\n" + "\t\"codes\": [\n" + "\t\t\"8567\"\n" + "\t]\n" + "}";
I would like using something like below eg arraylist, jsonObject, hashmap or jsonrray.
#Test
public void studentDetails() {
RestAssured.baseURI = " http://localhost:3000";
JSONObject mainObject = new JSONObject();
JSONArray array = new JSONArray();
array.put(Integer.parseInt("codes"), "8567");
JSONObject arrayItem = new JSONObject();
arrayItem.put("name", "nameValue");
arrayItem.put("age", "ageValue");
arrayItem.put("sex", "sexValue");
arrayItem.put("mobile", "mobileVal");
mainObject.put(String.valueOf(array), arrayItem);
given()
.body(mainObject.toString())
.when()
.post("/posts")
.then()
.assertThat()
.statusCode(200)
.contentType(ContentType.JSON);
}
I would recommend using a library like Jackson. You can create a POJO that will represent your JSON object which will allow you to go between JSON and Java objects easily. It will save you a lot of trouble and you won't have to worry about all of that awful formatting :)
Here is a more in depth tutorial - https://mkyong.com/java/jackson-how-to-parse-json/
Goto http://www.jsonschema2pojo.org/ and create POJOs and use them to send in request and response in object.

In Java how to easily get the value of a nested key from a JSON String / Object

I am using Java.
I have a string that I have converted to a JSON Object.
I want to extract the value of one of the Keys.
At the moment I am using this code:
String imageId = myJsonObject.getJSONObject("meta")
.getJSONObject("verification")
.getJSONObject("derivedData")
.getJSONArray("images")
.getJSONObject(0)
.getString("imageID");
This code works but surely there must be an easier way. In javascript I could access the value simply by writing this:
myJsonObject.meta.verification.derivedData.images[0].imageId
You may need to install library such as JsonPath to help you select values from a JSON object
An example to help understand better.
You can use external library Gson
Gson gson=new Gson();
/*You can convert to your DTO as well */
Map<Object,Object> map = gson.from(myJsonObject,Map.class);
Other way is using objectmapper example of fasterxml.
ObjectMapper objectMapper=new ObjectMapper();
/*You can convert to your DTO as well */
objectMapper.readValue(data, Map.class);
Try JsonNode by below step
String imageId= jsonNode.
findPath("meta")
.findPath("verification")
.findPath("derivedData")
.findPath("images")
.get (0).findPath ("imageID").asText ();
You need to use the 'Java API for JSON Binding' JSON-B instead of JSON-P. Using JSON-B you can serialize and deserialize between Java objects and data streams and access values of objects POJO style (similar to what you expect).
API details can be found here
A quick start tutorial can be found here and at many website only google search away..
I have created a small class for this purpose which can basically get value from json using a path only used google.gson
https://github.com/izeryab/JsonParser
Here is how to use this for getting nested value from json:
public class Main {
public static void main(String[] args) {
String json = "{\"data\":[{\"stuff\":[\n" + " { \"onetype\":[\n"
+ " {\"id\":1,\"name\":\"John Doe\"},\n" + " {\"id\":2,\"name\":\"Don Joeh\"}\n"
+ " ]},\n" + " {\"othertype\":[\n" + " {\"id\":2,\"company\":\"ACME\"}\n" + " ]}]\n"
+ "},{\"otherstuff\":[\n" + " {\"thing\":\n" + " [[1,42],[2,2]]\n" + " }]\n" + "}]}";
String name = JsonUtil.getJsonElementFromJsonStringUsingPath("data>0>stuff>0>onetype>0>name", json, ">").getAsString();
int id= JsonUtil.getJsonElementFromJsonStringUsingPath("data>0>stuff>0>onetype>0>id",json,">").getAsInt();
System.out.println("id : "+id);
System.out.println("name : "+name);
}
}
Corresponding JAVA DOCS:
https://izeryab.github.io/JsonParser/JsonUtil.html
You can use GSon, I've used it before (see below)
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
JsonArray jsonDataArray = rootobj.getAsJsonArray("data");
JsonPrimitive totalJson = rootobj.getAsJsonPrimitive("total");
JsonPrimitive nextJson = rootobj.getAsJsonPrimitive("next");

RestAssured JsonPath to String

Is there a way to convert the whole JSON path data to a string in Java?
I am working on APIs and their responses are in JSON format. It is easy to understand the JSON structure through Postman/WireShark but I am trying to run an API request through Java, grab the response, convert the raw response to JSON, convert JSON response to a string format and print it. The method '.getString()' is to access a particular element and not the whole data. The method '.toString()' does not work on JSON data either.
JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String id = json.get("id");
log.info("The id is " + id);
JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String complete_json_data = ???;
log.info("The complete json data is " + complete_json_data);
The code snippet which is mentioned "???" is what I was trying to achieve.
The methods which can convert a JsonPath object into a String are:
JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String complete_json_data = json.prettify();
and
JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String complete_json_data = json.prettyPrint();
var obj = { "field1":"foo", "age":55, "city":"Honolulu"};
var myJSON = JSON.stringify(obj);

Java Parse String

I have a String in a following format:
{"id":"1263e246711d665a1fc48f09","facebook_username":"","google_username":"814234576543213456788"}
but sometimes this string looks like:
{"id":"1263e246711d665a1fc48f09","facebook_username":"109774662140688764736","google_username":""}
How can I extract those values if I do not know the index of substrings as they will change for different cases?
That looks like json format, you should give a look to the Gson library by google that will parse that string automatically.
Your class should look like this
public class Data
{
private String id;
private String facebook_username;
private String google_username;
// getters / setters...
}
And then you can simply create a function that create the object from the json string:
Data getDataFromJson(String json){
return (Data) new Gson().fromJson(json, Data.class);
}
That String is formated in JSON (JavaScript Object Notation). Is a common language used to transfer data.
You can parse it using Google's library Gson, just add it to your class path .
Gson gson = new Gson();
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class); //The object you want to convert to.
https://github.com/google/gson
Check this out on how to convert to Java Object
Parsing as JSON notwithstanding, here's a pure string-based solution:
String id = str.replaceAll(".*\"id\":\"(.*?)\".*", "$1");
And similar for the other two, swapping id for the other field names.

converting java DTO list into JSON object

I have a DTO class like this:
package stbet.model.dto.db;
public class UKDashboardEventDTO implements Serializable{
private Long eventId;
private String meetingCode;
private String meetingName;
private String eventTime;
private String eventCode;
private String settleStatus;
private String category;
//getters and setters here:
#Override
public String toString() {
return "eventList{" + "eventId=" + eventId + ", meetingCode=" + meetingCode + ", meetingName=" + meetingName
+ "eventTime=" + eventTime + ", eventCode=" + eventCode + ", settleStatus=" + settleStatus
+ ", category=" + category + '}';
}
}
and I do some query stuff and create a java List of above DTO type.
for(Event ev : eventList){
dto = new UKDashboardEventDTO();
// some stuff
dto.setEventCode(ev.getEventCode());
dto.setEventId(ev.getId());
dto.setEventTime(ev.getEventTime());
dto.setMeetingName(ev.getMeeting().getMeetingName());
dto.setMeetingCode(ev.getMeeting().getMeetingCode());
eventDTOList.add(dto);
}
Then I add this list into a Hashmap and covert it into a JSON object like this:
Map map = new HashMap();
map.put("eventList",eventDTOList);
now convert into the json:
JSONObject obj = new JSONObject();
try {
obj.put("eventMap", map);
} catch (JSONException ex) {
}
out.println(obj);
out.flush();
out.close();
but when I get this object from client side, I am getting the dto package/object names list when parse or stringify the output instead of the proper dto values I passed from Java. What I get is this:
"{"eventMap":{"eventList":["stbet.model.dto.db.UKDashboardEventDTO#617538bb","stbet.model.dto.db.UKDashboardEventDTO#56dfaef9","stbet.model.dto.db.UKDashboardEventDTO#775889fd","stbet.model.dto.db.UKDashboardEventDTO#55cb7e41","stbet.model.dto.db.UKDashboardEventDTO#22ce0968","stbet.model.dto.db.UKDashboardEventDTO#4cb9cb2"]}}"
can you please let me know how to get the dto values I set from Java to client side json without java package name as above.
Firstly, you're using both JSON and GSON libraries, JSONException exists in JSON one and Expose annotation is in GSON. Please make sure you don't mix them as I won't work as intended.
Secondly, from Expose documentation
An annotation that indicates this member should be exposed for JSON serialization or deserialization.
This annotation has no effect unless you build Gson with a GsonBuilder and invoke GsonBuilder.excludeFieldsWithoutExposeAnnotation() method.
You should Override the toString field on the DTO, to print out all the individual field values.
This toString will be called when you do out.println(obj);
eg.
toString() {
// this method should list out all the attributes.
}
You should be using GSONBuilder to create the gson. Examples:
Gson: How to exclude specific fields from Serialization without annotations
Gson doesn't parse an exposed field
Here is a post on using GSON also
How to expose a method using GSon?
Finally I could fix it with your suggestions #Trynkiewicz Mariusz and #Paul John.
What I did was:
1. remove #Expose annotation
2. overridden the toString(){...} method.
3. remove the map implementation and used a List.
4. used gson.toJson(eventList);
this solved the issue and the output now is like :
[{
"eventId":167804,
"meetingCode":"V5PGB",
"meetingName":"SprintValley",
"eventTime":"15:38:00",
"eventCode":"10:08:00",
"category":"HR"
},
{
"eventId":167805,
"meetingCode":"V5PGB",
"meetingName":"SprintValley",
"eventTime":"15:50:00",
"eventCode":"10:20:00",
"category":"HR"
},..]
Thanks again guys...

Categories

Resources