jackson POJO有一个byte[]字段,但对应的JSON有一个string字段,如何将字符串转换为byte[]?

nuypyhwy  于 2023-10-20  发布在  其他
关注(0)|答案(2)|浏览(183)

我的POJO具有以下结构:

  1. class SomeName
  2. {
  3. .... // some fields
  4. private byte[] message;
  5. ....
  6. .... // some functions
  7. public byte[] getMessage()
  8. {
  9. return message;
  10. }
  11. }

我的JSON文件有一个名为“message”的字段,其中存储了一个String。目前我正在使用 * Jackson * 中的ObjectMapper。语法是

  1. ObjectMapper mapper = new ObjectMapper();
  2. SomeName myObjects = mapper.readValue(jsonData, new TypeReference<SomeName>() {});

有没有这种解决方案或替代解决方案(除了篡改POJO或JSON)?

hujrc8aj

hujrc8aj1#

您可以使用GSON Liberary这样做。如果你不是坚持Jackson图书馆。希望你能从这部分得到答案。

  1. public class JsonParse
  2. {
  3. public static void main(String... args)
  4. {
  5. Employee product = new Employee("JSON");
  6. Gson gson = new GsonBuilder().create();
  7. gson = new
  8. GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
  9. String result = gson.toJson(product);
  10. System.out.println(result);
  11. }
  12. }
  13. class Employee
  14. {
  15. @Expose
  16. private byte [] name;
  17. public Employee(String name)
  18. {
  19. this.name = name.getBytes();
  20. }
  21. }
展开查看全部
qyzbxkaa

qyzbxkaa2#

以下是使用GSON自定义解析器的示例:

  1. import com.google.gson.*;
  2. import java.lang.reflect.Type;
  3. import java.util.Map;
  4. class GsonStringToBytesExample {
  5. // POJO
  6. static class SomeName {
  7. public byte[] message;
  8. }
  9. // custom deserializer capable of converting json string field to pojo's byte[] field
  10. static class SomeNameDeserializer implements JsonDeserializer<SomeName> {
  11. private final static Gson gson = new Gson();
  12. @Override
  13. public SomeName deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
  14. // reading json fields to map
  15. Map<String, JsonElement> fieldsMap = json.getAsJsonObject().asMap();
  16. // reading json string message
  17. String messageStr = fieldsMap.get("message").getAsString();
  18. // creating bytes array from string
  19. byte[] messageBytes = messageStr.getBytes();
  20. // creating GSON's JsonElement from bytes array
  21. JsonElement dataBytesJsonElement = gson.toJsonTree(messageBytes);
  22. // substituting json "message" field with bytes array object
  23. fieldsMap.put("message", dataBytesJsonElement);
  24. // finally deserializing to POJO
  25. return gson.fromJson(json, typeOfT);
  26. }
  27. }
  28. public static void main(String[] args) {
  29. String json = """
  30. {"message":"hi"}
  31. """;
  32. Gson gson = new GsonBuilder()
  33. // registering custom deserializer
  34. .registerTypeAdapter(SomeName.class, new SomeNameDeserializer())
  35. .create();
  36. SomeName someName = gson.fromJson(json, SomeName.class);
  37. // here we have pojo with bytes array from string
  38. System.out.println(new String(someName.message));
  39. }
  40. }
展开查看全部

相关问题