1

I have Java bean:

public class User {
    private int id;
    private String name;
    private Address address;
    private List<String> favoriteBooks;
    private List<String> favoriteFilms;

    //getters and setter
}

I want convert instance of User class into JSON format, but selecting only three fields: id, name, favoriteBooks. I search some solution like

String[] fieldNames = { "id", "name", "favoriteBooks" };
JsonObject jo = new JsonObject(user, fieldNames);

How can I do it?

EDIT I found the answer here https://stackoverflow.com/a/13792700 with using Jackson library

Community
  • 1
  • 1
Paul
  • 580
  • 1
  • 7
  • 22
  • Possible duplicate of [How do I exclude fields with Jackson not using annotations?](https://stackoverflow.com/questions/13764280/how-do-i-exclude-fields-with-jackson-not-using-annotations) – cassiomolin Aug 05 '17 at 13:17

3 Answers3

2

You can try GSON library that allows you to convert beans to json and vice versa.

user3323654
  • 88
  • 2
  • 14
1

That's possible in Jersey 2 (MOXy or Jackson 2). For queries like this,

people/1234?select=familyName,givenName

it would return this json:

{
    "familyName": "Dowd",
    "givenName": "Andrew"
}

Find examples here.

steffen
  • 16,138
  • 4
  • 42
  • 81
0

Using jakson library you can mark properties with @JsonIgnore annotation to exclude it from converting.