Nihal Sharma
Nihal Sharma

Reputation: 2437

How to write a generic getObject() method for json string?

Got into a very basic issue. I have to convert json string to objects. I have a custom method as below which is expected to convert into corresponding class and throw an exception if it is not able to get the object out of it.

protected <T> T getObjectFromJson(Class<T> c, String json){
    try{
        Gson gson = new Gson();
        T object = gson.fromJson(json, c);
        return object;
    } catch (Exception e){
        throw new TMMIDClassConversionException(e.getCause(), e.getMessage());
    }
}

The issue is this method is not throwing exception if I am trying to convert json of a different class.

My class

public class CompanyCategoryMap {

private Integer id;
private int mid;
private String catKey;
private String catValue;
private int priority;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public int getMid() {
    return mid;
}

public void setMid(int mid) {
    this.mid = mid;
}

public String getCatKey() {
    return catKey;
}

public void setCatKey(String catKey) {
    this.catKey = catKey;
}

public String getCatValue() {
    return catValue;
}

public void setCatValue(String catValue) {
    this.catValue = catValue;
}

public int getPriority() {
    return priority;
}

public void setPriority(int priority) {
    this.priority = priority;
}

}

When I pass json string of Company rather than String of above class, it does not throw exception.

The string:

"{\"id\":6,\"name\":\"abc\",\"usersCount\":10,\"mid\":3,\"createdAt\":\"Sep 15, 2014 7:02:19 PM\",\"updatedAt\":\"Sep 15, 2014 7:02:19 PM\",\"active\":true,\"currency\":\"abc\",\"source\":\"unknown\",\"user_id\":1,\"tierId\":1}"

I think I am doing this conversion in a wrong way. What is the suggested way of doing it?

Upvotes: 0

Views: 395

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

Take for example:

class Foo {
    private String value;
}

class Bar {
    private String value;
}

and

String json = "{\"value\" : \"whatever\"}";
new Gson().fromJson(json, Foo.class);
new Gson().fromJson(json, Bar.class);

Why should Gson reject any of these?

Gson is setup to perform a best effort to deserialize the given JSON into an instance of the given Class. It will map as many fields as it finds. If none are found, that's too bad.

Other libraries like Jackson do the opposite. By default, Jackson rejects any JSON which doesn't contain a mapping for every given class property. You can also configure it to ignore some properties.

Keep doing what you are doing. As the application writer, you should know when to use a Class instance with the appropriate JSON source.

Upvotes: 1

Related Questions