Removing Custom Serialisation for JSON objects - java

I currently have a custom serialiser. Purpose of my custom serialiser is to format my JSON object from this: {"id":["21","22", 23"]} to this {"id":"21,22,23"}.
My current implementation of my custom serialiser:
public static class ListSerialiser implements JsonSerializer<List<Member>> {
#Override
public JsonElement serialize(List<Member> src, Type type, JsonSerializationContext context) {
JsonObject object = new JsonObject();
List<String> memberId = new ArrayList<>(src.size());
for (Member member : src) {
memberId.add("" + Member.getId());
}
String memberIdAsString = TextUtils.join(",", memberId);
object.addProperty("[%s]", memberIdAsString);
return object;
}
}
Although my implementation got me what I wanted, just out of curiosity, I was wondering if there's a way to serialise without having to use Text Utils or string formatters to achieve this outcome: {"id":"21,22,23"}

There are a lot of ways to join strings, you can see most of them here
My favourite is:
String memberIdAsString = memberId.stream().collect(Collectors.joining(","));

Related

Parse a JSON structure with symbol instead of a string for an attribute

I am working on an HTTP Rest query.
Wikipedia API returns a JSON. The problem is the JSON structure returned by Wikipedia.
https://en.wikipedia.org/w/api.php?action=parse&section=0&prop=text&format=json&page=pizza
This is the JSON obtained via a rest request to the Wikipedia API. To view the full JSON, you can click on the above link.
{
"parse":
{
"title":"Pizza",
"pageid":24768,
"text":{"*":"<div class=\...>"}
}
}
I would parse this using a custom deserializer which I haven't got a chance to test. Trying to parse with simple Gson like the following return null;
Result res = new Gson(str,Result.class);
I have created the classes like the following:
public class Result
{
private Parse parse;
}
public class Parse
{
private String title;
private int pageid;
private Text text;
}
public class Text{
private String *;// what should I call this attribute.
}
My plan is to add a custom deserializer like the following:
public class TextBaseDeserializer implements JsonDeserializer<Text> {
#Override
public RespondentBase deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
return jsonDeserializationContext.deserialize(jsonElement.get("*"),Text.class);
}
}
I am using Gson to parse this, like the following:
Gson tmp = new GsonBuilder().registerTypeAdapter(Text.class, new TextBaseDeserializer());
// let's assume that str is the string obtained following Rest based request from Java.
Result res = tmp.parse(str,Result.class);
I have done all the above code to handle the symbolic JSON attribute.
My question is how to parse such a JSON. In the above example, the attribute is a *
As mentioned in a comment, you should annotated field with #SerializedName("*").
You can name the field whatever you want. We'll just name it star below, but maybe all is better, since * might be a wildchar? Doesn't really matter, just choose whatever name you like.
class Text
{
#SerializedName("*")
private String star;
}
Test
String str = "{\"parse\":{\"title\":\"Pizza\",\"pageid\":24768,\"text\":{\"*\":\"<div class=\\\"mw-parser-output\\\">...</div>\"}}}";
Gson tmp = new GsonBuilder().create();
Result res = tmp.fromJson(str, Result.class);
System.out.println(res.getParse().getText().getStar());
Output
<div class="mw-parser-output">...</div>

Use Gson/Retrofit on SerializedName which is unknown beforehand

I need to get data from a badly designed web API which returns the list of objects in the form of JSON object:
{
"29593": { ..object to parse },
"29594": { ..object to parse },
"29600": { ..object to parse }
}
I need to create POJO for this response, but the issue is that these integers are changing, they are like object IDs. I don't know how to extract these integers from the JSON keys and then use the inner JSON objects further in another POJO class (I know basic Gson mapping when the key has a fixed value).
Is it even possible?
The solution is to use a custom JsonDeserializer from gson library, here is a example:
public class MyAwesomeDeserializer implements JsonDeserializer<MyModel> {
public MyModel deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject eJson = json.getAsJsonObject();
Set<String> keys = eJson.keySet();
MyModel myModel = new MyModel();
for (String key: keys) {
JsonObject asJsonObject = eJson.get(key).getAsJsonObject();
ItemOfMyModel itemOfMyModel = context.deserialize(asJsonObject, ItemOfMyModel.class);
myModel.addItemOfMyModel(itemOfMyModel);
}
return myModel;
}
}
and dont forget to add your custom deserializer as a type adapter to gson builder:
Gson gson = new GsonBuilder()
.registerTypeAdapter(MyModel.class, new MyAwesomeDeserializer())
.create()

How do I treat empty Strings as null objects with GSON?

I'm retrieving comments from the Reddit API. The model is threaded such that each Comment can internally have a List of Comments, named replies. Here's an example of how a JSON response would look:
[
{
"kind":"Listing",
"data":{
"children":[
{
"data":{
"body":"comment",
"replies":{
"kind":"Listing",
"data":{
"children":[
{
"data":{
"body":"reply to comment",
"replies":""
}
}
]
}
}
}
}
]
}
}
]
Here is how I model this with POJOs. The response above would be considered a List of CommentListings.
public class CommentListing {
#SerializedName("data")
private CommentListingData data;
}
public final class CommentListingData {
#SerializedName("children")
private List<Comment> comments;
}
public class Comment {
#SerializedName("data")
private CommentData data;
}
public class CommentData {
#SerializedName("body")
private String body;
#SerializedName("replies")
private CommentListing replies;
}
Note how the bottom level CommentData POJO refers to another CommentListing called "replies".
This model works until GSON reaches the last child CommentData where there are no replies. Rather than providing a null, the API is providing an empty String. Naturally, this causes a GSON exception where it expects an object but finds a String:
"replies":""
Expected BEGIN_OBJECT but was STRING
I attempted to create a custom deserializer on the CommentData class, but due to the recursive nature of the model it seems not to reach the bottom levels of the model. I imagine this is because I'm using a separate GSON instance to complete deserialization.
#Singleton
#Provides
Gson provideGson() {
Gson gson = new Gson();
return new GsonBuilder()
.registerTypeAdapter(CommentData.class, new JsonDeserializer<CommentData>() {
#Override
public CommentData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject commentDataJsonObj = json.getAsJsonObject();
JsonElement repliesJsonObj = commentDataJsonObj.get("replies");
if (repliesJsonObj != null && repliesJsonObj.isJsonPrimitive()) {
commentDataJsonObj.remove("replies");
}
return gson.fromJson(commentDataJsonObj, CommentData.class);
}
})
.serializeNulls()
.create();
}
How can I force GSON to return a null instead of a String so that it doesn't try to force a String into my POJO? Or if that's not possible, manually reconcile the data issue? Please let me know if you need additional context or information. Thanks.
In general your code looks good, but I would recommend a few things:
Your type adapters should not capture Gson instances from outside. Type adapter factories (TypeAdapterFactory) are designed for this purpose. Also, in JSON serializers and deserializers you can implicitly refer it through JsonSerializationContext and JsonDeserializationContext respectively (this avoids infinite recursion in some cases).
Avoid modification JSON objects in memory as much as possible: serializers and deserializers are just a sort of pipes and should not bring you surprises with modified objects.
You can implement a generic "empty string as a null" type deserializer and annotate each "bad" field that requires this kind of deserialization strategy. You might consider it's tedious, but it gives you total control wherever you need it (I don't know if Reddit API has some more quirks like this).
public final class EmptyStringAsNullTypeAdapter<T>
implements JsonDeserializer<T> {
// Let Gson instantiate it itself
private EmptyStringAsNullTypeAdapter() {
}
#Override
public T deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context)
throws JsonParseException {
if ( jsonElement.isJsonPrimitive() ) {
final JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if ( jsonPrimitive.isString() && jsonPrimitive.getAsString().isEmpty() ) {
return null;
}
}
return context.deserialize(jsonElement, type);
}
}
And then just annotate the replies field:
#SerializedName("replies")
#JsonAdapter(EmptyStringAsNullTypeAdapter.class)
private CommentListing replies;

Parsing JSON String as simple as possible with GSON

Using GSON, how can i return a single key from a Multidimensional Json String?
Here is the Multidimensional Json String:
{"statusCode":0,"statusDescription":"OK","data":{"user":{"id":xxx,"company_id":xxx,"account_type":"5","enable_locations":true,"intuit_user_id":null,"nick_name":"xxx","is_owner":"1","enabled":"1"},"session_token":"xxx"}}
I want to return the "session_token" key value.
I'm trying this:
class app {
static class Response {
String session_token;
}
public void getSessionToken() {
String x = {"statusCode":0,"statusDescription":"OK","data":{"user":{"id":xxx,"company_id":xxx,"account_type":"5","enable_locations":true,"intuit_user_id":null,"nick_name":"xxx","is_owner":"1","enabled":"1"},"session_token":"xxx"}}
Response r = new Gson().fromJson(x, Response.class);
System.out.println(r.session_token);
}
}
But with this, my r.session_token returns null.
You would need to use Gson's JsonParser class directly and extract the data from the parse tree:
String myJsonString = "{\"name\":\"john\",\"lastname\":\"smith\"}";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(myJsonString);
JsonObject jsonObject = element.getAsJsonObject();
String lastName = jsonObject.get("lastname").getAsString();
System.out.println(lastName);
That said, it's debatable whether this would save you any real time over:
(edited from comments below):
class App {
static class Response {
String lastname;
}
public static void main(String[] args) {
String myJsonString = "{\"name\":\"john\",\"lastname\":\"smith\"}";
Response r = new Gson().fromJson(myJsonString, Response.class);
System.out.println(r.lastname);
}
}
Gson will silently ignore the fact that there's more data in the JSON than you're interested in, and later on you might be interested in it, in which case it's trivial to add fields to your Response class.
Edit due to question changing:
You have a JSON object. It contains a field data whose value is an object. Inside that object you have a field session_token that you're interested in.
Either you have to navigate to that field through the parse tree, or you have to create Java classes that all will map to. The Java classes would resemble (at the bare minimum):
class Response {
Data data;
}
class Data {
String session_token;
}

JSON Object representation

I am new to JSON. so please help me....
I am trying to write a Rest service that returns a Person object as follows:
PersonJSONAdapter implements JsonSerializer<Person>, JsonDeserializer<Person>
{
public JsonElement serialize(final Person src, final Type typeOfSrc, final JsonSerializationContext context)
{
if (src == null)
return null;
final JsonObject retVal = new JsonObject();
retVal.addProperty("firstname", src.getFirstname());
retVal.addProperty("lastname", src.getLastname());
return retVal;
}
so with this the output of the JSON looks like:
{ "firstname" : "XXX",
"lastname" : "YYY"
}
How can I make this one look like
“Person”
{
“firstname”: “XXX”,
"lastname":"YYY"
}
Thanks for looking...
That's not valid JSON. JSON is only a data representation and has no knowledge of meta data such as type information.
The closest you can get is by explicitly adding the type as an extra property, such as:
{ "#type":"Person", "firstname":"XXX", "lastname":"YYY" }
This means however that you'll have to select the right class when you deserialize it. You might want to check out some libraries, but I think they either require you to specify the class yourself or to add custom annotations to serializable classes.

Categories