简体   繁体   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[]?

My POJO has the following structure:我的 POJO 具有以下结构:

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

And my JSON file has the field named 'message' which has a String stored in it.我的 JSON 文件有一个名为“message”的字段,其中存储了一个字符串。 Currently I am using ObjectMapper from com.fasterxml.jackson.databind.ObjectMapper .目前我正在使用com.fasterxml.jackson.databind.ObjectMapper 中的ObjectMapper 。 The syntax being语法是

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

Is there a way with this solution or an alternate solution (other than tampering the POJO or the JSON) for this?有没有办法使用此解决方案或替代解决方案(除了篡改 POJO 或 JSON)?

You can do like this way using GSON Liberary.您可以使用 GSON Liberary 以这种方式进行操作。 If you are not stick to jackson library.如果你不坚持杰克逊图书馆。 Hope you will get your answer from this part.希望你能从这部分得到你的答案。

 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