2014-04-29 3 views
7

사용하여 객체 내의 된 JSONObject를 직렬화 할 수 없습니다 나는 다음 클래스가 있습니다JSON 잭슨

class A{  
    String abc; 
    String def; 
    // appropriate getters and setters with JsonProperty Annotation 
} 

를 내가 잘 작동 Jacksons objectMapper.writeValueAsString(A)를 호출합니다.

는 지금은 다른 인스턴스 멤버 추가해야합니다

class A{  
    String abc; 
    String def; 
    JSONObject newMember; // No, I cannot Stringify it, it needs to be JSONObject 
    // appropriate getters and setters with JsonProperty Annotation 
} 

을하지만 직렬화 때, 나는 예외를 얻고있다 ":

org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer 

내가 JSONNode을 시도했지만이 {outerjson로 출력했다

{innerjson} "}은 {outerjson : {innerjson}}이 아닙니다.

JSONObject 내에서 위의 출력 즉 JSONObject를 얻기 위해 Jackson을 사용할 수 있습니까? 당신은 POJO 나지도에 된 JSONObject를 대체 할 수없는 경우

enter image description here

+1

주어진 입력에서 예상되는 출력을 표시 할 수 있습니까? –

+2

Jackson이 제공 한'''ObjectNode'''를 사용하지 않으시겠습니까? – oceansize

답변

0

음, 당신은 custom serializer을 작성할 수 있습니다. 다음은 예입니다

public class JacksonJSONObject { 

    public static class MyObject { 
     public final String string; 
     public final JSONObject object; 

     @JsonCreator 
     public MyObject(@JsonProperty("string") String string, @JsonProperty("object") JSONObject object) { 
      this.string = string; 
      this.object = object; 
     } 

     @Override 
     public String toString() { 
      return "MyObject{" + 
        "string='" + string + '\'' + 
        ", object=" + object + 
        '}'; 
     } 
    } 

    public static void main(String[] args) throws IOException { 
     ObjectMapper mapper = new ObjectMapper(); 
     SimpleModule module = new SimpleModule("org.json"); 
     module.addSerializer(JSONObject.class, new JsonSerializer<JSONObject>() { 
      @Override 
      public void serialize(JSONObject value, JsonGenerator jgen, SerializerProvider provider) throws IOException { 
      jgen.writeRawValue(value.toString()); 
      } 
     }); 
     module.addDeserializer(JSONObject.class, new JsonDeserializer<JSONObject>() { 
      @Override 
      public JSONObject deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { 
       Map<String, Object> bean = jp.readValueAs(new TypeReference<Map<String, Object>>() {}); 
       return new JSONObject(bean); 
      } 
     }); 
     mapper.registerModule(module); 
     JSONObject object = new JSONObject(Collections.singletonMap("key", "value")); 
     String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new MyObject("string", object)); 

     System.out.println("JSON: " + json); 
     System.out.println("Object: " + mapper.readValue(json, MyObject.class)); 
    } 
} 

출력 :

JSON: { 
    "string" : "string", 
    "object" : {"key":"value"} 
} 
Object: MyObject{string='string', object={"key":"value"}} 
0

대신 된 JSONObject의 사용 JsonNode.

JsonNode jsonNode = JsonLoader.fromString(YOUR_STRING);