2012-07-18 2 views
16

mimetype과 value의 두 필드가있는 JSON을 만들고 싶습니다. 값 필드는 값으로 바이트 배열을 사용해야합니다.jackson을 사용하여 json에서 바이트 배열 보내기

{ 

    "mimetype":"text/plain", 

    "value":"dasdsaAssadsadasd212sadasd"//this value is of type byte[] 

} 

이 작업을 어떻게 수행 할 수 있습니까?

현재로서는 바이트 배열을 String으로 변환하고 JSON을 형성하기 위해 toString() 메서드를 사용하고 있습니다.

답변

3

이진 데이터를 문자열로 변환하는 Base64을 사용할 수 있습니다. 대부분의 프로그래밍 언어에는 base64 인코딩 및 디코딩 구현이 있습니다. 브라우저에서 디코딩/인코딩하려면 this question을 참조하십시오.

+1

그러나 Base64에는 다양한 종류가 있음을 유의하십시오. –

25

JSON 구문 분석에 Jackson을 사용하는 경우 데이터 바인딩을 통해 byte[]을 Base64로 인코딩 된 문자열로 /에서 자동 변환 할 수 있습니다.

낮은 수준의 액세스를 원할 경우 JsonParserJsonGenerator은 JSON 토큰 스트림 수준에서 동일한 작업을 수행하는 이진 액세스 방법 (writeBinary, readBinary)을 사용합니다. 자동 접근 방식에 대한

, 같은 POJO을 고려

public class Message { 
    public String mimetype; 
    public byte[] value; 
} 

및 JSON을 만들기 위해, 당신이 할 수 있습니다 :

OutputStream out = ...; 
new ObjectMapper().writeValue(out, msg); 
:

Message msg = ...; 
String jsonStr = new ObjectMapper().writeValueAsString(msg); 

또는, 더 일반적으로를 작성합니다

+0

는 샘플 코드를 제공 할 수 있습니다 ...? –

+0

바이트 [] 필드가있는 POJO 중? 답변에 추가됩니다 ... – StaxMan

10

다음과 같이 자신 만의 CustomSerializer를 작성할 수 있습니다.

public class ByteArraySerializer extends JsonSerializer<byte[]> { 

@Override 
public void serialize(byte[] bytes, JsonGenerator jgen, 
     SerializerProvider provider) throws IOException, 
     JsonProcessingException { 
    jgen.writeStartArray(); 

    for (byte b : bytes) { 
     jgen.writeNumber(unsignedToBytes(b)); 
    } 

    jgen.writeEndArray(); 

} 

private static int unsignedToBytes(byte b) { 
    return b & 0xFF; 
    } 

} 

이 코드는 Base64 문자열 대신 부호없는 바이트 배열 표현을 반환합니다.

{ 
    "mimetype": "text/plain", 
    "value": [ 
     81, 
     109, 
     70, 
     122, 
     90, 
     83, 
     65, 
     50, 
     78, 
     67, 
     66, 
     84, 
     100, 
     72, 
     74, 
     108, 
     89, 
     87, 
     48, 
     61 
    ] 
} 

PS : 당신의 POJO와 함께 사용하는 방법

: 그것은 출력의의 여기

public class YourPojo { 

    @JsonProperty("mimetype") 
    private String mimetype; 
    @JsonProperty("value") 
    private byte[] value; 



    public String getMimetype() { return this.mimetype; } 
    public void setMimetype(String mimetype) { this.mimetype = mimetype; } 

    @JsonSerialize(using= com.example.yourapp.ByteArraySerializer.class) 
    public byte[] getValue() { return this.value; } 
    public void setValue(String value) { this.value = value; } 


} 

그리고는 예입니다이 시리얼 라이저는 I에 유래에서 발견 된 일부 답변의 혼합이다 .