我有一个以编码形式传入URL的参数。 所以,如果JSON是
{"size":{"value":"5\"x10\" Kraft (250 Envelopes) Value Pack"}, "color":{"value":""},"packSize":{"value":""},"style":{"value":""}}
然后以编码形式:
%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
当我使用我的Java代码时,我会这样:
{"size":{"value":"5\"x10\" Kraft (250 Envelopes) Value Pack"}, "color":{"value":""},"packSize":{"value":""},"style":{"value":""}}
我有一个VariantContainer类,我想分配这些值。
所以我尝试了两种方法,但是我得到了例外。
方法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);
}
方法2:
try {
variantContainer = gson.fromJson(variant, VariantContainer.class);
} catch (Exception ex) {
logger.error(ex);
}
它给出例外:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 10
让我知道,遗漏了什么。我怎样才能以最佳方式获得它?
VariantContainer类
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);
}
}