简体   繁体   中英

Jackson - Map JSON string field to class/pojo that has only one field (a string)

I am writing a JSON interface/library to work with Bugzilla's webservice.

Is this possible using an annotation or something? Or am I to write a custom deserializer for every instance like this?

I've tried doing some research, and found some information about a Value Instantiator or using constructors, but isn't using constructors anti-bean like? I've found documentation to be sparse or hard to understand with the newer features.

Example:

public class Bug{
  // Bug info, strings, ints, yadda yadda.
 private User creator;   // creator of the bug, json is like   {"creator":"blahblah@email.com"}
}

public class User{
 private String username;
}
//insert setter/getter.

The reason I am using a pojo for One field is because this User class is extended by another that has more fields. While I can implement a constructor to achieve this effect, doing so means I have to implement the same constructor for all other subclasses. I feel like there is something similar to @JsonValue but for setting (I tried JsonCreator on my setter but still got the same error as I have been getting below).

"Can not instantiate value of type [simple type, class User], from String value; no single-String constructor/factory method"

Thanks.

Use @JsonCreator for deserializing and use @JsonValue for Serializing. Have tested the code. Please make sure that getJsonString() is public method.

For example:

public class User{
    private String username;

    @JsonValue
    public String getJsonString() {
         return username;
    }

    @JsonCreator
    private static User parseJson(String jsonStr) {
        User u = new User();
        u.username = jsonStr;
        return u;
    }

    public static void main(String[] args) {
        User u = new User();
        u.userName = "Niraj";

        ObjectMapper m = new ObjectMapper();
        String jsonString = m.writeValueAsString(u);
        User u1 = m.readValue(jsonString, User.class);
    }
}

You don't need to use a @JsonCreator or @JsonValue or a construtor, Jackson will work OTTB with javabean methods: Try this instead:

public class User{
    private String username;

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public static void main(String[] args) throws Exception {
        User u = new User();
        u.setUsername("name");

        ObjectMapper m = new ObjectMapper();
        String userString = m.writeValueAsString(u);
        System.out.println(userString);
        User u1 = m.readValue(userString, User.class);
        System.out.println(u1.getUsername());
    }
}

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