简体   繁体   中英

Issues Converting String to javax.json.JsonString

I have a class that looks something like this

    private byte[] profilePicture;
    private ProfileType profileType;
    private String profileHandle;
    private String personalEmail;
    private Address address;    

To convert this to Json using javax.json is like this:

    JsonObject payloadObject = Json.createObjectBuilder()
    .add("profilePicture", profilePictureEncoded)
    .add("profileType", profileType.ordinal())
    .add("profileHandle", profileHandle)
    .add("personalEmail", personalEmail)
    .add("webAppEmail", webappEmail)
    .add("address", address.produceJsonPayload())
    .build();

All good!! except sometimes there is no profile picture so I wanted to build this incrementally ie

    JsonObject payloadObject = Json.createObjectBuilder().build();
    if(profilePicture != null)
    {
        final String profilePictureEncoded = ..... //encode the image
        payloadObject.put("profilePicture",profilePictureEncoded);
    }

problem is you cant because I can't cast profilePictureEncoded to a JsonString

Has anyone got something like this working? Or do I need to use another Json Library?

Damien

You can just get a reference to the JsonObjectBuilder .

JsonObjectBuilder payloadObjectBuilder = Json.createObjectBuilder();

wait until you have everything while constructing

if(profilePicture != null)
{
    final String profilePictureEncoded = ..... //encode the image
    payloadObject.add("profilePicture",profilePictureEncoded);
}

and then build()

JsonObject payloadObject = payloadObjectBuilder.build();

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