I am having a parameter that am passing in URL, in encoded form. So If JSON is
{"size":{"value":"5\"x10\" Kraft (250 Envelopes) Value Pack"}, "color":{"value":""},"packSize":{"value":""},"style":{"value":""}}
Then in encoded form it will be :
%7B%22size%22%3A%7B%22value%22%3A%225%5C%22x10%5C%22%20Kraft%20(250%20Envelopes)%20Value%20Pack%22%7D%2C%20%22color%22%3A%7B%22value%22%3A%22%22%7D%2C%22packSize%22%3A%7B%22value%22%3A%22%22%7D%2C%22style%22%3A%7B%22value%22%3A%22%22%7D%7D
Which when I get in my Java code I get like this :
{"size":{"value":"5\"x10\" Kraft (250 Envelopes) Value Pack"}, "color":{"value":""},"packSize":{"value":""},"style":{"value":""}}
And am having a class VariantContainer where I want to assign these values.
So I tried two ways, but am getting exception.
Approach 1 :
try {
# variant is value I get from URL
JsonElement variantRequestJson = new JsonParser().parse(variant);
variantContainer.setSize(variantApiRequestJson.getAsJsonObject().
get("size").getAsJsonObject().get("value").toString());
# Similarly other variations, but its giving null pointer exception
} catch (Exception ex) {
logger.error(ex);
}
Approach 2 :
try {
variantContainer = gson.fromJson(variant, VariantContainer.class);
} catch (Exception ex) {
logger.error(ex);
}
It gives exception :
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 10
Let me know, what am missing. How can I get it in best way ?
VariantContainer class
import com.google.gson.Gson;
public class VariantContainer {
private String size;
private String color;
private String packSize;
private String style;
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getPackSize() {
return packSize;
}
public void setPackSize(String packSize) {
this.packSize = packSize;
}
@Override
public String toString() {
Gson gson = new Gson();
return gson.toJson(this);
}
}