Deserialize JSON string into String Array - java

How to get this string and put into String Array or HashMap? Any reference?
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"location" : "Authorization",
"locationType" : "header",
"message" : "The domain policy has disabled third-party Drive apps",
"reason" : "domainPolicy"
} ],
"message" : "The domain policy has disabled third-party Drive apps"
}
====
This is my solution for Jackson:
public class TheErrorModel {
public int code;
public Collection<Error> errors;
public String message;
public TheErrorModel() {
}
public TheErrorModel(String json)
throws Exception {
ObjectMapper mapper = new ObjectMapper();
TheErrorModelother = mapper.readValue(json, TheErrorModel.class);
this.code = other.code;
this.errors = other.errors;
this.message = other.message;
}
}
class Error {
public String domain;
public String location;
public String locationType;
public String message;
public String reason;
}
TheErrorModel theErrorModel = new TheErrorModel(json);
So I get something like theErrorModel.message :D

You can try to use GSON http://code.google.com/p/google-gson/ , It is pretty simple to use. You should just create class structure for this json schema.
import com.google.gson.Gson;
class YourErrorsJSON{
private String domain
private String location;
private String locationType;
private String message;
private String reason
}
class YourJSON {
private int code;
private YourErrorsJSON[] errors;
private String message;
}
Gson gson = new Gson();
YourJSON obj = gson.fromJson(json, YourJSON.class);

Try this ::
JSONObject yourObj = JSONObject.fromString(input_string);
String code = yourObj.get("code"); // code will have a value 403

Related

Parsing Entire AWS SQS Record using GSON

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;
}

ACCEPT_EMPTY_STRING_AS_NULL_OBJECT with List field

with Jackson, I'm trying to properly deserialize a JSON which contains empty string as no value values. Herein an example:
{
"code" : "REQ500",
"description" : "Problem with Service",
"params" : ""
}
and the bean I would get:
public final class MyError {
#JsonProperty("code")
private String code;
#JsonProperty("description")
private String description;
#JsonProperty("params")
private List<String> params;
// [CUT]
public void setParams(List<String> params) {
this.params = params;
}
}
Using ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, I've create an object mapper with
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
.registerModule(new SimpleModule().addDeserializer(LocalDate.class, new DateDeserializer()));
expecting to have params = null, but deserialization doesn't work. Herein the error I got:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize instance of `java.util.ArrayList` out of VALUE_STRING token
at [Source: (String)"{
"code" : "REQ500",
"description" : "Problem with Service",
"params" : ""
}"; line: 4, column: 14] (through reference chain: solutions.infinitec.fabrick.models.common.MyError["params"])
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
Any hints on how to solve this issue? Am I wrong somewhere?
Thank you in advance for suggestions.
I tried it using ACCEPT_SINGLE_VALUE_AS_ARRAY and it works as expected.
ObjectMapper om = new ObjectMapper();
om.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
MyJson asString = om.readValue("{\n"
+ " \"code\" : \"REQ500\",\n"
+ " \"description\" : \"Problem with Service\",\n"
+ " \"params\" : \"\"\n"
+ "}", MyError.class);
MyJson asArray = om.readValue("{\n"
+ " \"code\" : \"REQ500\",\n"
+ " \"description\" : \"Problem with Service\",\n"
+ " \"params\" : [\"\"]\n"
+ "}", MyError.class);
The only thing you have to handle is the response containing just a single element in params which is empty.
Another way could be this definition of MyError:
public class MyError {
#JsonProperty("code")
private String code;
#JsonProperty("description")
private String description;
private List<String> params;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<String> getParams() {
return params;
}
#JsonProperty("params")
private void setParams(JsonNode params) {
if (params.isArray()) {
this.params = new ArrayList<>();
for(JsonNode child : params) {
this.params.add(child.asText());
}
}
}
}
I'd try using
OBJECT_MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
As shown in "Cannot deserialize instance of java.util.ArrayList"
Just implement a setter method which accept string:
public void setParams(String params) {
this.params = null;
}
if want to accept array:
public void setParams(String[] params) {
this.params = Arrays.asList(params);
}

Serialize only the data you need from json

I get some data form JSON. I can't change JSON, it is foreign API. JSON...
"apply" : {
"type" : "submit",
"form" : "#pageForm",
"data" : {
"ctl00$MainContentArea$fld_offerCode" : "%promo"
},
"submit" : "#OfferCodeSubmit",
"response" : {
"type" : "html",
"total" : "#orderItemsDisplay .totals:last"
}
},
or
"apply" : {
"type" : "post",
"url" : "https:\/\/www.4wheelparts.com\/shoppingcart.aspx",
"submit" : "#ctl00_ContentPlaceHolder1_btnCouponCode",
"contentType" : "application\/x-www-form-urlencoded",
"data" : {
"__VIEWSTATE" : "",
"ctl00$ContentPlaceHolder1$tbCouponCode" : "%promo",
"ctl00$ContentPlaceHolder1$btnCouponCode" : "Redeem"
}
}
I want save JSON to database, and use "serialize data". But parameter "data" constantly changing. How can I serialize parameter "type", "url", "submit", and is't serialize parametr "data"?
I want to add to my DB this form...
"type" : "post"
"url" : "https:\/\/www.4wheelparts.com\/shoppingcart.aspx"
"data" : {
"__VIEWSTATE" : "",
"ctl00$ContentPlaceHolder1$tbCouponCode" : "%promo",
"ctl00$ContentPlaceHolder1$btnCouponCode" : "Redeem"
}
So I serialize the data...
public class Apply
{
#SerializedName("type")
#Expose
private String type;
#SerializedName("submit")
#Expose
private String submit;
#SerializedName("timeout")
#Expose
private Long timeout;
....How data should look like???
Or am I going to need to move the another way?
dont add data in your model and that will be ok. i suggest you to use Gson library. and do as below :
Apply apply = (new Gson()).fromJson(jsonString);
jsonString is a string variable containing your json.
you can import Gson library by adding this to your gradle file:
compile 'com.google.code.gson:gson:2.8.0'
If you need only few specific data,Can follow this
jsonObj = new JSONObject(strRequestPacket);
requiredData = jsonObj.getString("requiredData");
If you need to map to your entity class,then follow this
Gson gson = new Gson();
if(mob_farmerStatus !=null){
User user = gson.fromJson(strRequestPacket, User.class);
System.out.println("user:::"+user);
public class Apply
{
#SerializedName("type")
#Expose
private String type;
#SerializedName("submit")
#Expose
private String submit;
#SerializedName("timeout")
#Expose
private Long timeout;
#SerializedName("timeout")
#Expose
private Data data;
// Setter Getters here
}
public class Data
{
private String vIEWSTATE;
private String ctl00$ContentPlaceHolder1$tbCouponCode;
private String ctl00$ContentPlaceHolder1$btnCouponCode;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getVIEWSTATE() {
return vIEWSTATE;
}
public void setVIEWSTATE(String vIEWSTATE) {
this.vIEWSTATE = vIEWSTATE;
}
public String getCtl00$ContentPlaceHolder1$tbCouponCode() {
return ctl00$ContentPlaceHolder1$tbCouponCode;
}
public void setCtl00$ContentPlaceHolder1$tbCouponCode(String ctl00$ContentPlaceHolder1$tbCouponCode) {
this.ctl00$ContentPlaceHolder1$tbCouponCode = ctl00$ContentPlaceHolder1$tbCouponCode;
}
public String getCtl00$ContentPlaceHolder1$btnCouponCode() {
return ctl00$ContentPlaceHolder1$btnCouponCode;
}
public void setCtl00$ContentPlaceHolder1$btnCouponCode(String ctl00$ContentPlaceHolder1$btnCouponCode) {
this.ctl00$ContentPlaceHolder1$btnCouponCode = ctl00$ContentPlaceHolder1$btnCouponCode;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
I solved it problem with help:
import okhttp3.ResponseBody;
public interface ConfigsBodyRequest
{
#GET("config.json")
Observable<ResponseBody> getResponse();
}
I get json without serialization, and than parse json
//item - (String) content of json file.
JSONObject jsonObject = new JSONObject(item);
String required = jsonObject.getString("apply");
And now required is equal to String : {"type":"submit","form":"#pageForm","data":{"ctl00$MainContentArea$fld_offerCode":"%promo"}},
And i just save in DB this string, this is what I needed. Thanks all.

Unable to invoke no-args constructor for Product.class

I am Using GSON and Volley library for networking in my android application but while converting the Json response to Model classes using Gson i am getitng the following error:
88-2006/ E/Volley﹕ [121] NetworkDispatcher.run: Unhandled exception java.lang.RuntimeException: Unable to invoke no-args constructor for class [Lcom.example.model.Product;. Register an InstanceCreator with Gson for this type may fix this problem.
java.lang.RuntimeException: Unable to invoke no-args constructor for class [Lcom.example.model.Product;. Register an InstanceCreator with Gson for this type may fix this problem.
these are my POJO classes i am using :
Product.java
public class Product {
private String status;
private List<Result> results = new ArrayList<Result>();
private Pagination pagination;
public Product(){}
// getters and setters
}
Pagination.java
public class Pagination {
private String first;
private String previous;
private String next;
private String last;
public Pagination(){}
}
Result.java
public class Result {
private String id;
private Properties properties;
public Result{}
}
Properties.java
public class Properties {
private String qbcode;
private String name;
private String purchasedate;
private String vendor;
private String thumbnail;
public Properties(){}
}
I have gone through the existing questions which are same like this , as per answers i have found i added the no arg constructor to all the classes but still i am getting the error please help me in solving this issue
The Json String:
{
"status" : "OK",
"results" : [ {
"id" : "IzIzOjE=",
"properties" : {
"qbcode" : "IN-1-1",
"name" : "Test Name",
"purchasedate" : "2015-05-21",
"vendor" : "Test Vendor",
"thumbnail" : "http://en.wikipedia.org/static/images/project-logos/enwiki.png"
}
}, {
"id" : "IzIzOjI=",
"properties" : {
"qbcode" : "IN-1-2",
"name" : "Test Name",
"purchasedate" : "2015-05-21",
"vendor" : "Test Vendor",
"thumbnail" : "http://en.wikipedia.org/static/images/project-logos/enwiki.png"
}
}, {
"id" : "IzIzOjM=",
"properties" : {
"qbcode" : "IN-1-3",
"name" : "Test Name",
"purchasedate" : "2015-05-21",
"vendor" : "Test Vendor",
"thumbnail" : "http://en.wikipedia.org/static/images/project-logos/enwiki.png"
}
},{
"id" : "IzIzOjU=",
"properties" : {
"qbcode" : "IN-1-5",
"name" : "Test Name",
"purchasedate" : "2015-05-21",
"vendor" : "Test Vendor",
"thumbnail" : "http://en.wikipedia.org/static/images/project-logos/enwiki.png"
}
} ],
"pagination" : {
"first" : "/list?size=20",
"previous" : "/list?start=IzIzOjE=&size=20",
"next" : "/list?start=IzIzOjQx&size=20",
"last" : "/list?start=IzIzOjYx&size=20"
}
}
Add default constructor for all classes. Example:
public class Product{
public Product(){
}
}
problem solved, I am doing a foolish call To Gson because i am obtaining a Product class that contains list of other Classes(Result.class etc) but i am sending Product[].class to Gson to convert Hence it thrown exception.
Your model having private attribute you must create setter for the same or create constructor with all parameter like below:
public class Product {
private String status;
private List<Result> results = new ArrayList<Result>();
private Pagination pagination;
public void setStatus(String status) {
this.status = status;
}
public void setResults(List<Result> results) {
this.results = results;
}
public void setPagination(Pagination pagination) {
this.pagination = pagination;
}
}
or
public class Product {
private String status;
private List<Result> results = new ArrayList<Result>();
private Pagination pagination;
public Product(String status, List<Result> results, Pagination pagination) {
this.status = status;
this.results = results;
this.pagination = pagination;
}
}

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

Categories

Resources