简体   繁体   中英

Set JSONArray into String in POJO class using GSON

I have a jsonarray and for that i have created pojo class. Now, i want to set jsonarray into a string. When i am doing that it throws error of The JsonDeserializer StringTypeAdapter failed to deserialize json object given the type class java.lang.String . And this question is differ because i want to set that jsonarray into String So, any one have any idea ?

Gson.toJson() returns a String..

So like..

String myArrayAsAString = gsonInstance.toJson(myJsonArray);

Is that what you mean?

u can set the method uself. public class BookDeserializer implements JsonDeserializer {

@Override
public Book deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
  throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();

final JsonElement jsonTitle = jsonObject.get("title");
final String title = jsonTitle.getAsString();

final String isbn10 = jsonObject.get("isbn-10").getAsString();
final String isbn13 = jsonObject.get("isbn-13").getAsString();

final JsonArray jsonAuthorsArray = jsonObject.get("authors").getAsJsonArray();
final String[] authors = new String[jsonAuthorsArray.size()];
for (int i = 0; i < authors.length; i++) {
  final JsonElement jsonAuthor = jsonAuthorsArray.get(i);
  authors[i] = jsonAuthor.getAsString();
}

final Book book = new Book();
book.setTitle(title);
book.setIsbn10(isbn10);
book.setIsbn13(isbn13);
book.setAuthors(authors);
return book;
}
}    

http://www.javacreed.com/gson-deserialiser-example/

Say you have an array of productInfo:

List<ProductInfo> productInfos = new ArrayList<>();
// fill your productInfos, etc.

Then you want to get String representation of productInfos' JsonArray:

JsonArray productInfoJsonArray = (JsonArray) new Gson().toJsonTree(productInfos,
            new TypeToken<List<ProductInfo>>() {
            }.getType());

productInfoJsonArray.getAsString();

I'm not entirely sure about what you're trying to achieve, but I hope that above snippet helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM