Parsing Entire AWS SQS Record using GSON - java

I have been trying unsuccessfully now to parse this message. Using the AWS Simple Queue Service API, I follow instructions and do the following...
for(Message m : Messages){
System.out.println(m.getBody());
}
This returns a JSON string in this structure:
{
"Records": [
{
"EventSource": "",
"EventVersion": "",
"EventSubscriptionArn": "",
"Sns": {
"Type": "",
"MessageId": "",
"TopicArn": "",
"Subject": null,
"Message": ""
"Timestamp": "",
"SignatureVersion": "",
"Signature": "”
"SigningCertUrl": "",
"UnsubscribeUrl": "",
"MessageAttributes": {}
}
}
]
}
I have been trying to parse this entire thing to a Java Object using GSON so that I can extract the "Message" parameter (which also contains JSON) and then use GSON to parse that (done and works when I just pass that text directly).
These are the classes I set up, but this will not work -- Each one has public getters and setters.....
Records Class:
public class Records {
public ArrayList<ExceptionMessages> exceptionMessages = new ArrayList<ExceptionMessages>();
public ArrayList<ExceptionMessages> getExceptionMessages() {
return exceptionMessages;
}
public void setExceptionMessages(ArrayList<ExceptionMessages> exceptionMessages) {
this.exceptionMessages = exceptionMessages;
}
Message Class:
public class ExceptionMessages {
public String EventSource;
public String EventVersion;
public String EventSubscriptionArn;
public Sns messageJSON;
}
Sns Class (where the message is stored):
public class Sns {
public String Type;
public String MessageId;
public String TopicArn;
public String Subject;
public String Message;
public String Timestamp;
public String SignatureVersion;
public String Signature;
public String SigningCertUrl;
public String UnsubscribeUrl;
public String MessageAttributes;
}
I get a null pointer exception when trying to .get(0) of the ArrayList so it's empty and parsing did not take place.
Here is how I'm calling it...
I'm sending m.getBody() to a parsing method and attempting to parse like this:
Gson gson = new Gson();
Records record = new Records();
gson.fromJson(JSONString.replaceAll("\\s+", ""), Records.class);

The structure should be
class RecordContainer {
ArrayList<Record> Records;
}
class Record {
public String EventSource;
public String EventVersion;
public String EventSubscriptionArn;
public Sns Sns;
}
class Sns {
public String Type;
public String MessageId;
public String TopicArn;
public String Subject;
public String Message;
public String Timestamp;
public String SignatureVersion;
public String Signature;
public String SigningCertUrl;
public String UnsubscribeUrl;
public MessageAttributes MessageAttributes;
}

Related

how to edit/change POST response?

I got a school assignment asking me to change the content of JSON Response
from
{"name" : "Bob"}
to
{"greeting" : "Hello, Bob"}
this is my ResponseDTO
public class HelloWorldResponseDTO {
private String name;
}
and this is my Entity
public class HelloWorld {
private String name;
public HelloWorldResponseDTO convertToResponse() {
return new HelloWorldResponseDTO(this.name);
}
}

GSON Json Mapping for HashMap Nested Object

I have a json context like below:
{
"data": {
"details": {
"en-CA": {
"languageCode": "en-CA",
"isPrimaryLocale": false
},
"en-US": {
"languageCode": "en-US",
"isPrimaryLocale": true,
"languageDisplayName": "English (United States)",
}
}
}
}
To map it with GSON in java:
I created this classes:
public class ApiResponseSingleDto
{
private ResponseDetail data;
}
public class ResponseDetail
{
private ResponseDetails details;
#Getter
public static class ResponseDetails
{
public HashMap<String, LocaleDetail> row = new HashMap<>();
}
}
public class LocaleDetail
{
private String languageCode;
private Boolean isPrimaryLocale;
private String languageDisplayName;
}
When I try to map json to Java POJO class, HashMap doesn't work. Is there any suggestion?
To map it:
GSON.fromJson("...json", Type type...);
Just try to replace:
public class ApiResponseSingleDto
{
private ResponseDetail data;
}
public class ResponseDetail
{
private Map<String, LocaleDetail> details;
}
public class LocaleDetail
{
private String languageCode;
private Boolean isPrimaryLocale;
private String languageDisplayName;
}
Also json seems to be incorrect: "languageDisplayName": "English (United States)",
should be just "languageDisplayName": "English (United States)"
One more note: I believe you should have public fields or at least getters for them

Gson string with key

I am using Gson to get convert the object to json string, and its working fine but when I am sending that json to a webservice method using post, I have to add the post method's parameter name in the string.
Example:
jsonString I get from Gson new Gson().toJson(requestDataDTO) :
{
"req": {
"AppId": "2",
"ThirdParty": "3",
"UserId": "1",
"UserToken": "4"
},
"req1": {
"AppId": "-33",
"ThirdParty": "3",
"UserId": "1",
"UserToken": "4"
}
}
jsonString I want :
{
"requestDataDTO": {
"req": {
"AppId": "2",
"ThirdParty": "3",
"UserId": "1",
"UserToken": "4"
},
"req1": {
"AppId": "-33",
"ThirdParty": "3",
"UserId": "1",
"UserToken": "4"
}
}
}
for now I am adding this "requestDataDTO" string at the start of json string I got from Gson.
is there a way to achieve this ?
Assuming you have an object which looks somehow like this:
package com.dominikangerer.q25077756;
import com.google.gson.annotations.SerializedName;
public class RequestDataDTO {
// {"AppId":"2","ThirdParty":"3","UserId":"1","UserToken":"4"}
#SerializedName("AppId")
private String appId;
#SerializedName("ThirdParty")
private String thirdParty;
#SerializedName("UserId")
private String userId;
#SerializedName("UserToken")
private String userToken;
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getThirdParty() {
return thirdParty;
}
public void setThirdParty(String thirdParty) {
this.thirdParty = thirdParty;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserToken() {
return userToken;
}
public void setUserToken(String userToken) {
this.userToken = userToken;
}
}
The easiest and also for me most readable solution would be to create an wrapper/container Class which contains a HashMap (key/value) like this:
package com.dominikangerer.q25077756;
import java.util.HashMap;
public class RequestDataDTOContainer {
private HashMap<String, RequestDataDTO> requestDataDTO = new HashMap<String, RequestDataDTO>();
public HashMap<String, RequestDataDTO> getRequestDataDTO() {
return requestDataDTO;
}
public void setRequestDataDTO(HashMap<String, RequestDataDTO> requestDataDTO) {
this.requestDataDTO = requestDataDTO;
}
public void putRequestDataDTO(String key, RequestDataDTO value){
this.requestDataDTO.put(key, value);
}
}
To run it simply test it with a main like this:
// enable pretty printing
Gson gson = new GsonBuilder().setPrettyPrinting().create();
// too lazy to fill the objects by hand
String reqJson = "{\"AppId\":\"2\",\"ThirdParty\":\"3\",\"UserId\":\"1\",\"UserToken\":\"4\"}";
String req1Json = "{\"AppId\":\"-33\",\"ThirdParty\":\"3\",\"UserId\":\"1\",\"UserToken\":\"4\"}";
// deserialize it with gson
RequestDataDTO req = gson.fromJson(reqJson, RequestDataDTO.class);
RequestDataDTO req1 = gson.fromJson(req1Json, RequestDataDTO.class);
// initiliaze the container
RequestDataDTOContainer container = new RequestDataDTOContainer();
// adding the 2 req objects with the certain key
container.putRequestDataDTO("req", req);
container.putRequestDataDTO("req1", req1);
// Print it as pretty json
System.out.println(gson.toJson(container));
You are now more flexibility if you want to add more meta information like a whole meta object or similar without adding a hardcoded String to that json.
You can find the whole Example in this github repository: Java Stackoverflow Answers by DominikAngerer

http 400 bad request exception for converting json to java object representation

When I attempt to send json to server I receive http 400 bad request exception.
The format of the json is :
{
"role": "home",
"name": "group1: False, group2: False"
}
The java class to represent this json is :
public class Params {
private String role;
private String[] name;
public String[] getName() {
return name;
}
public void setName(String[] name) {
this.name = name;
}
public String getRole() {
return profileRuleName;
}
public void setRole(String role) {
this.role = role;
}
}
Is this format of the java class correct in order to represent this json ?
You can construct an array in JSON like this:
{
"role": "home",
"name": ["group1","group2"]
}
Here's a link to the JSON format that shows arrays (and objects and everything else)
http://json.org

Java json parse

Well I've been trying for like 3 hours now. Using lots of apis it still doesn't work.
I'm trying to parse
{
"id": 8029390,
"uid": "fdABNhroHsr0",
"user": {
"username": "Skrillex",
"permalink": "skrillex"
},
"uri": "/skrillex/cat-rats",
"duration": 305042,
"token": "VgA2a",
"name": "cat-rats",
"title": "CAT RATS",
"commentable": true,
"revealComments": true,
"commentUri": "/skrillex/cat-rats/comments/",
"streamUrl": "http://media.soundcloud.com/stream/fdABNhroHsr0?stream_token=VgA2a",
"waveformUrl": "http://w1.sndcdn.com/fdABNhroHsr0_m.png",
"propertiesUri": "/skrillex/cat-rats/properties/",
"statusUri": "/transcodings/fdABNhroHsr0",
"replacingUid": null,
"preprocessingReady": null
}
in to an array/list.
Any help?
I'm using Jackson from http://codehaus.org/ and so far it has lived up to all my needs.
You don't quite deal with json as raw strings in an arraylist, but rather as POJOs, here's a quick example with a subset of your json.
public class JacksonExample {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String text = "{ \"id\": 8029390, \"user\": { \"username\": \"Skrillex\" } }";
ObjectMapper mapper = new ObjectMapper();
Pojo pojo = mapper.readValue(text, Pojo.class);
System.out.println(pojo.id);
System.out.println(pojo.user.username);
}
}
class Pojo {
public String id;
public User user;
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public static class User {
public String username;
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
}
}
The mapper creates a Pojo object with the values filled in. Then you can use that object for anything you need.
Here are a couple of links for the Jackson project:
http://jackson.codehaus.org/
http://wiki.fasterxml.com/JacksonInFiveMinutes
The latest all in one JAR is here:
http://jackson.codehaus.org/1.9.1/jackson-all-1.9.1.jar
You should try JavaJson from source forge... you can parse that this way:
JsonObject json = JsonObject.parse("...");
/*
* or also JsonObject.parse(inputStream);
*/
then you can get fields this way:
String title = json.getString("title");
String username = json.get("user", "username").toString();
and so on. here's the link: https://sourceforge.net/projects/javajson/

Categories

Resources