繁体   English   中英

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

[英]POJO has a byte[] field, but JSON corresponding to it has string field. How to convert the string to byte[]?

我的 POJO 具有以下结构:

class SomeName
{
       .... // some fields
       private byte[] message;
       ....
       .... // some functions
       public byte[] getMessage() 
       {
           return message;
       }
}

我的 JSON 文件有一个名为“message”的字段,其中存储了一个字符串。 目前我正在使用com.fasterxml.jackson.databind.ObjectMapper 中的ObjectMapper 。 语法是

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

有没有办法使用此解决方案或替代解决方案(除了篡改 POJO 或 JSON)?

您可以使用 GSON Liberary 以这种方式进行操作。 如果你不坚持杰克逊图书馆。 希望你能从这部分得到你的答案。

 public class JsonParse
 {
    public static void main(String... args)
    {
        Employee product = new Employee("JSON");
        Gson gson = new GsonBuilder().create(); 
        gson = new 
        GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        String result = gson.toJson(product);
        System.out.println(result);
    }
 }

class Employee
{

  @Expose
  private byte [] name;

  public Employee(String name)
  {
     this.name = name.getBytes();
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM