Stuck on getting JSONArray from a JSONObject - java

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

Related

toJson() of GSON library returning wrong json

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

GSON not returning key name, only value (Java)

I'm trying to format some String data to JSON using the GSON api, as shown in my returnJson() method:
import com.google.gson.*;
import com.google.gson.annotations.SerializedName;
public class HUKD {
#SerializedName("title")
public String title;
#SerializedName("Deal URL")
public String dealUrl;
#SerializedName("Product URL")
public String productUrl;
#SerializedName("Image URL")
public String imgUrl;
#SerializedName("Description")
public String description;
#SerializedName("Temperature")
public String temperature;
#SerializedName("EAN")
public String ean;
#SerializedName("Price")
public String price;
#SerializedName("Amazon Price")
public String amazonPrice;
#SerializedName("Price Difference")
public String priceDifference;
#SerializedName("Amazon URL")
public String amazonUrl;
public HUKD(String title, String dealUrl, String productUrl, String imgUrl, String description, String temperature, String ean, String price, String amazonPrice, String priceDifference, String amazonUrl) {
this.title = title;
this.dealUrl = dealUrl;
this.productUrl = productUrl;
this.imgUrl = imgUrl;
this.description = description;
this.temperature = temperature;
this.ean = ean;
this.price = price;
this.amazonPrice = amazonPrice;
this.priceDifference = priceDifference;
this.amazonUrl = amazonUrl;
}
public String returnJson(){
System.out.println("********TESTING OBJECTS*************");
String[] jsonBuilder = new String []{title, dealUrl, productUrl, imgUrl, description, temperature, ean, price, amazonPrice, priceDifference, amazonUrl};
Gson gson = new GsonBuilder().setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
String json = gson.toJson(jsonBuilder );
return json;
}
However, GSON will only return the value, not the key:
[
"Philips shm3560/10 on ear headphones £8.99 from Argos",
"http://www.hotukdeals.com/deals/philips-shm3560-10-headphones-8-99-from-argos-2390246?aui\u003d1063",
"http://www.hotukdeals.com/visit?m\u003d5\u0026q\u003d2390246",
"http://static.hotukdeals.com/images/threads/2390246_1.jpg",
"Argos cat no- 108/7390\nhttp://www.argos.co.uk/webapp/wcs/stores/servlet/SearchMobile?storeId\u003d10151\u0026catalogId\u003d25051\u0026langId\u003d110\u0026searchTerm\u003d108%2F7390",
"171°",
"8712581626211",
"£8.99",
"£12.59",
"Argos is cheaper than Amazon by £3.60",
"http://www.amazon.co.uk/Philips-SHM3560-10-Pc-headset-Shm3560/dp/B008FSE6EU%3FSubscriptionId%3DAKIAILN2TPM667MBMJAQ%26tag%3Dgithubcomthis-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB008FSE6EU"
]
I've tried to get around this by adding the SerializedName annotation as suggested in the "JSON Field Naming Support" section of the API documentation here, but I'm still not having any luck. Ideally, I'd like the JSON formatted like so:
"title":"Philips shm3560/10 on ear headphones £8.99 from Argos"
(and so on...), i.e. with the key name printed as specified in the #SerializedName annotation in the field declaration.
Thanks!
You are not serializing your object, but array of Strings so you see proper result of this serialization. If you want to serialize your object you must use something like this:
public String returnJson(){
Gson gson = new GsonBuilder().setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
String json = gson.toJson(this);
return json;
}

JSON parsing through GSON returns null values

I am trying to read the values of a JSON output.
This is the JSON output:
{"nameOfSummoner":{"id":56529189,"name":"test","profileIconId":550,"summonerLevel":30,"revisionDate":1422110739000}}
And with the following code I am trying to read it:
final Connector connector = new Connector();
String response = connector.connect("link"); // (Returns a String value of the JSON)
final Gson gson = new Gson();
final Summoner summoner = gson.fromJson(response, Summoner.class); //Summoner is a model class
System.out.println(summoner);
Summoner class:
public class Summoner {
private String name;
private long profileIconId;
private long summonerLevel;
private long revisionDate;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public long getProfileIconId() {
return profileIconId;
}
public void setProfileIconId(final long profileIconId) {
this.profileIconId = profileIconId;
}
public long getSummonerLevel() {
return summonerLevel;
}
public void setSummonerLevel(final long summonerLevel) {
this.summonerLevel = summonerLevel;
}
public long getRevisionDate() {
return revisionDate;
}
public void setRevisionDate
(long revisionDate) {
this.revisionDate = revisionDate;
}
#Override
public String toString() {
return "Summoner{" +
"name='" + name + '\'' +
", profileIconId=" + profileIconId +
", summonerLevel=" + summonerLevel +
", revisionDate=" + revisionDate +
'}';
}
}
And I get the following output on the console:
Summoner{name='null', profileIconId=0, summonerLevel=0, revisionDate=0}
I have sadly no idea why this happens. Any help I get is appreciated. I am fairly sure it has to do with the JSON output that "nameOfSummoner" is on top and maybe that's why it does not read what is below.
As mentioned by #PeterMmm , your input is a map with 1 key-value pair.
You need to Create another POJO with Summoner object as attribute:
public class Sample {
private Summoner nameOfSummoner;
//getters and setters
}
and then try parsing. Or, you could create a Map and parse.
Map<String, Summoner> responseObj = new HashMap<String, Summoner>();
responseObj= gson.fromJson(response, responseObj.class);
Summoner obj = responseObj.get("nameOfSummoner");
You will also need to have "id" attribute in Summoner class I believe, else gson will throw an exception.

Tweak JSON or GSON?

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]]

Serializing JSON string to object

I am trying to parse through a JSON string and convert it to the following POJO:
package apicall;
//POJO representation of OAuthAccessToken
public class OAuthAccessToken {
private String tokenType;
private String tokenValue;
public OAuthAccessToken(String tokenType,String tokenValue) {
this.tokenType=tokenType;
this.tokenValue=tokenValue;
}
public String toString() {
return "tokenType="+tokenType+"\ntokenValue="+tokenValue;
}
public String getTokenValue() {
return tokenValue;
}
public String getTokenType() {
return tokenType;
}
}
In order to do this I have written the following code:
Gson gson=new Gson();
String responseJSONString="{\"access_token\" : \"2YotnFZFEjr1zCsicMWpAA\",\"token_type\" : \"bearer\"}";
OAuthAccessToken token=gson.fromJson(responseJSONString, OAuthAccessToken.class);
System.out.println(token);
When I run the code, I get the following output:
tokenType=null
tokenValue=null
Instead of
tokenType=bearer
tokenValue=2YotnFZFEjr1zCsicMWpAA
I don't understand if there's anything I've done wrong. Please help.
You can get the expected result by annotating your fields like:
#SerializedName("token_type")
private final String tokenType;
#SerializedName("access_token")
private final String tokenValue;
How is Gson supposed to know how to populate your object? You don't have a no-arg constructor, and the fields of your object don't match the fields in the JSON object.
Make your object as following:
public class OAuthAccessToken {
private String accessToken;
private String tokenType;
OAuthAccessToken() {
}
...
}
The class should have the exact field name as the json, so if your json have 2 keys: "access_token" and "token_type", the class should have 2 fields:
private String access_token;
private String token_type;
And, of course you need to change the getters/setters accordingly.

Categories