I am using GSON library to pass json to server as header.
But it is not generating my expected json.
My Pojo class "TestRequest.java" is like:
public class TestRequest {
private String mobileNumber;
public TestRequest(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
}
Here is my code to call the GSON class to make json:
Gson gson = new Gson();
TestRequest tt = new TestRequest("+8801913000000");
String json = gson.toJson(tt);
My expected json is :
{"mobileNumber":"+8801913000000"}
But I am getting:
{"aIf":"+8801913000000"}
Note: This code was working perfectly 2 days before.
Try to change your pojo class like
public class TestRequest implements Serializable {
#SerializedName("mobileNumber")
private String mobileNumber;
public TestRequest(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
}
Let me know if not work
Related
Ok. I've used response = restTemplate.exchange(url, HttpMethod.POST,request, String.class) to send some request to resource server. Under that, I have used System.out.println("Response------" + response.getBody()); . With that executed, I'm receiving a string that is at the same time some kind of JSON object. Can you explain to me how can I convert it into some kind of entity so I can store it into my database? Thanks in advance!
That string that I'm receiving is like this: {"access_token":"example...","expires_in":28800,"refresh_token":"example...","scope":"example...","token_type":"Bearer","user_id":"example..."}
You can use ObjectMapper from Jackson(com.fasterxml.jackson.databind.ObjectMapper)
ObjectMapper objectMapper = new ObjectMapper();
YourClass obj = objectMapper.readValue(yourJsonString, YourClass.class);
Try using Gson:
Gson gson = new Gson();
QuestionAnswerDTO questionAnswerDTOs = gson.fromJson(json, new TypeToken<QuestionAnswerDTO>() {
}.getType());
Here QuestionAnserDTO contains the same field as that of in JSON String.
You need to create the desired entity with jaxb, like:
#XmlRootElement
public final class Entity {
private Integer id;
private String name;
public final Integer getId() {
return this.id;
}
public final void setId(Integer id) {
this.id = id;
}
public final String getName() {
return this.name;
}
public final void setName( String name) {
this.name = name;
}
}
And then you can do simple like:
response = restTemplate.exchange(url, HttpMethod.POST,request, Entity.class);
I have a JSON response that looks something like:
And a Subscription POJO class and inside it, is an Arraylist of the "subscriptionPlans":
SubscriptionDetails.java
#Expose()
#SerializedName("subscriptionPlans")
public ArrayList<SubscriptionPlans> subscriptionPlans;
public ArrayList<SubscriptionPlans> getSubscriptionPlans() {
return subscriptionPlans;
}
#Override
public String toString() {
return "SubscriptionDetails{" +
"subscriptionPlans=" + subscriptionPlans +
'}';
}
SubscriptionPlans.java
#SerializedName("plan_name")
#Expose
public String planName;
#SerializedName("description")
#Expose
public String description;
#SerializedName("amount")
#Expose
public String amount;
public String getPlanName() {
return planName;
}
public String getDescription() {
return description;
}
public String getAmount() {
return amount;
}
I'm using Gson to get the data from the JSON and populate it to the various POJO classes like so:
Gson gson = new Gson();
SubscriptionDetails subscriptionDetails = gson.fromJson(String.valueOf(jsonObject.getJSONArray("subscriptionPlans")), SubscriptionDetails.class);
ArrayList<SubscriptionPlans> subscriptionPlans = subscriptionDetails.getSubscriptionPlans();
String amount = subscriptionPlans.get(0).getAmount();
however, I get the error response,
java.lang.IllegalStateException:Expected BEGIN_OBJECT but was BEGIN_ARRAY at line column 2 path $
What I'm I missing or not doing correct here?
pass to GSON the entire string, not just String.valueOf(jsonObject.getJSONArray("subscriptionPlans")):
SubscriptionDetails subscriptionDetails = gson.fromJson(String.valueOf(jsonObject), SubscriptionDetails.class);
Getting empty java object while populating the following type of Json.
a.json:
------
{
"queries": [{
"query": {
"id": "q1",
"description": "Fire query to get the Auth token !!"
}
}
],
"executeQuery": ["q2", "q3"]
}
Query.java :
-----------
Note : #Data will take care of creating setter getter by Lombok library.
#Data
public class Query {
#Expose #SerializedName("id")
String id;
#Expose #SerializedName("description")
String description;
}
GRT.java :
----------
#Data
public class GRT{
#Expose #SerializedName("queries")
List<Query> queries ;
#Expose #SerializedName("executeQuery")
List<String> executeQuery;
}
Client call :
----------------------------------------------
private void readJson() throws IOException{
String fileName = "a.json";
// Get Gson object
Gson gson = newGsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
// read JSON file data as String
String fileData = new String(Files.readAllBytes(Paths.get(fileName)));
// parse json string to object
GenericRestTestDefinition grtDef = gson.fromJson(fileData, GenericRestTestDefinition.class);
System.out.println(grtDef.toString());
}
Printing the following :
GRT(queries=[Query(id=null, description=null)], executeQuery=[q2, q3])
Dont know why GRT-> Query Object is not getting populated ????
The proper JSON for this would look like this..
{
"queries":
[
{"id":"q1","description":"Fire query to get the Auth token"},
{"id":"q2","description":"Fire query to get the Auth token 2"}
]
}
public class Test {
public static void main(String[] args) throws Exception {
readJson();
}
private static void readJson() throws IOException {
String json ="{\"queries\":[{\"id\":\"q1\",\"description\":\"Fire query to get the Auth token\"}]}";
// Get Gson object
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
GRT grt = new GRT();
grt.setQueries(Arrays.asList( new Query[]{new Query("q1", "Fire query to get the Auth token")} ));
System.out.println(gson.toJson(grt));
// parse json string to object
GRT grtDef = gson.fromJson(json, new TypeToken<GRT>(){}.getType());
System.out.println(grtDef.queries.get(0));
}
}
If you can't change the json file format you can use this pattern:
#Data
public class GRT{
#Expose #SerializedName("queries")
private List<QueryWrapper> queries = new ArrayList<>();
public List<Query> getQueries() {
return queries.stream().map(it->it.query).collect(Collectors.toList());
}
#Expose #SerializedName("executeQuery")
List<String> executeQuery = new ArrayList<>();
}
#Data
public class QueryWrapper {
#Expose #SerializedName("query")
Query query;
}
#Data
public class Query {
public
#Expose #SerializedName("id")
String id;
#Expose #SerializedName("description")
String description;
}
I have integrated Gson to create the json used in a request for an android application.
Here is my model class
public class TwitterUser {
#Expose
public String gid;
public String icon_url;
public Boolean is_app_user;
#Expose
public String displayName;
public TwitterUser(String l, String i, String url, Boolean app_user) {
gid = i;
displayName = l;
icon_url = url;
is_app_user = app_user;
}
public TwitterUser(String l, String i) {
gid = i;
displayName = l;
}
public String getGid() {
return gid;
}
public void setGid(String gid) {
this.gid = gid;
}
public String getIcon_url() {
return icon_url;
}
public void setIcon_url(String icon_url) {
this.icon_url = icon_url;
}
public Boolean getIs_app_user() {
return is_app_user;
}
public void setIs_app_user(Boolean is_app_user) {
this.is_app_user = is_app_user;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
Here is how i create the json request
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
gson.toJson(twitterUser));
But when I send the request to the server - the order will be rejected. I have to change the request's field order to stay:
gid
displayName
but gson creates other way around, is there any way to achieve this.
Gson doesn't support definition of property order out of the box, but there are other libraries that do. Jackson allows defining this with #JsonPropertyOrder, for example.
But of course Gson has it's way so you can do it by creating your very own Json serializer:
public class TwitterUserSerializer implements JsonSerializer<TwitterUser> {
#Override
public JsonElement serialize(TwitterUser twitterUser, Type type, JsonSerializationContext context) {
JsonObject object = new JsonObject();
object.add("gid", context.serialize(twitterUser.getGid());
object.add("displayName", context.serialize(twitterUser.getDisplayName());
// ...
return object;
}
}
Then of course you need to pass this serializer to Gson during Setup like this:
Gson gson = new GsonBuilder().registerTypeAdapter(TwitterUser.class, new TwitterUserSerializer()).excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(twitterUser);
See also:
Gson User Guide - Custom serializers and deserializers
I have a Java app that is getting back the following JSON from a 3rd party RESTful web service:
{
"widgets":[
[
{
"id":25128,
"status":"always",
"uuid":"96f62edd-fa8a-4267-8ffb-14af0d37de26"
}
],
[
{
"id":25200,
"status":"always",
"uuid":"78553c9e-398f-495a-8fb8-ada0fb297844"
}
],
[
{
"id":25128,
"status":"never",
"uuid":"b1e3deb2-a842-4cba-8272-458d15efb394"
}
]
]
}
And trying to convert it into a List<Widget> using GSON:
public class Widget {
#SerializedName("id")
private Long id;
#SerializedName("status")
private String status;
#SerializedName("uuid")
private String uuid;
// Getters & setters, etc.
}
Here is my mapper code:
String jsonResponse = getJsonFromWebService();
Gson gson = new Gson();
List<Widget> widgets = gson.fromJson(jsonResponse, new TypeToken<List<Widget>>(){}.getType());
When I run this, I'm getting the following error:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
Obviously, I either need to manipulate the JSON string before sending it to my GSON mapper code, or I need to configure GSON to handle the "unexpected" JSON, but I'm not sure which is easier/more appropriate. If I need to "massage" the JSON string, not sure what I need to do to make GSON play nicely with it. And if I need to configure GSON, not sure what to do there either. Any ideas? Thanks in advance.
What's wrong is that you're ignoring the root JSON Object with a single JSON Property "widgets". Try deserializing your data into this object instead:
public class WidgetList {
#SerializedName("widgets")
private List<List<Widget>> widgets;
}
Massaging it to the below format works for me
[
{
'id':25128,
'status':'always',
'uuid':'96f62edd-fa8a-4267-8ffb-14af0d37de26' },
{
'id':25200,
'status':'always',
'uuid':'78553c9e-398f-495a-8fb8-ada0fb297844' },
{ 'id':25128,
'status':'never',
'uuid':'b1e3deb2-a842-4cba-8272-458d15efb394'
}
]
As the below demonstrates
public class TryMe {
public static void main(String[] args) {
Gson gson = new Gson();
List<Widget> widgets = gson.fromJson(json,
new TypeToken<List<Widget>>() {
}.getType());
System.out.println(widgets);
}
}
class Widget {
#SerializedName("id")
private Long id;
#SerializedName("status")
private String status;
#SerializedName("uuid")
private String uuid;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
#Override
public String toString() {
return "Widget [id=" + id + ", status=" + status + ", uuid=" + uuid
+ "]";
}
}
Giving the below resp
[Widget [id=25128, status=always, uuid=96f62edd-fa8a-4267-8ffb-14af0d37de26], Widget [id=25200, status=always, uuid=78553c9e-398f-495a-8fb8-ada0fb297844], Widget [id=25128, status=never, uuid=b1e3deb2-a842-4cba-8272-458d15efb394]]