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 ?
-
Could you incluse some of your code?Bas Peeters– Bas Peeters2015-09-25 06:24:10 +00:00Commented Sep 25, 2015 at 6:24
-
3stackoverflow.com/questions/4586229/…Balwinder Singh– Balwinder Singh2015-09-25 06:24:38 +00:00Commented Sep 25, 2015 at 6:24
-
But, i want to set that jsonarray into a string variable. So, can i do that?Ronak Joshi– Ronak Joshi2015-09-25 06:35:34 +00:00Commented Sep 25, 2015 at 6:35
Add a comment
|
3 Answers
Gson.toJson() returns a String..
So like..
String myArrayAsAString = gsonInstance.toJson(myJsonArray);
Is that what you mean?
1 Comment
Ronak Joshi
Where i put this code? I mean i called this when my json came,
Gson gson = new GsonBuilder().serializeNulls().create(); ProductInfo item = gson.fromJson(response.toString(), POJO_Class.class); and my POJO_Class have getter and setter methods.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;
}
}
2 Comments
Ronak Joshi
But for this i have to make separate classes, because my response is too long, and it have more than 4 array. So, for all i have to make classes ?
tiny sunlight
maybe u should provide the json ,the POJO class and the place u want to set that jsonarray into String
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.