2011-12-16 2 views
0

자바에서 개체를 JSONObject (org.json.JSONObject)로 변환하는 데 문제가 있습니다.자바 : JSONObject 상속

개체 X가 자식 개체 Y입니다. "새로운 JSONObject (this) .ToString()"을 만들 때 JSONObject에서 만든 개체 X (자식)의 특성 만 만듭니다.

부모 클래스 :

import org.json.JSONObject; 

public class Class1 { 
private String name; 
private int number; 

public String getName() { 
    return name; 
} 
public void setName(String name) { 
    this.name = name; 
} 
public int getNumber() { 
    return number; 
} 
public void setNumber(int number) { 
    this.number = number; 
} 
public String toString(){ 
    return new JSONObject(this).toString(); 
} 
} 

아이 클래스 :

import org.json.JSONObject; 
public class Class2 extends Class1 { 

private String attrChildString; 
private int attrChildInt; 
/** 
* @param args 
*/ 
public static void main(String[] args) { 
    Class2 class2 = new Class2(); 
    class2.setName("test"); 
    class2.setNumber(5); 
    class2.setAttrChildInt(10); 
    class2.setAttrChildString("child"); 

    System.out.println("toString child : " + class2.toString()); 
    System.out.println("toString Parent : " + class2.toStringParent()); 
} 
public String getAttrChildString() { 
    return attrChildString; 
} 
public void setAttrChildString(String attrChildString) { 
    this.attrChildString = attrChildString; 
} 
public int getAttrChildInt() { 
    return attrChildInt; 
} 
public void setAttrChildInt(int attrChildInt) { 
    this.attrChildInt = attrChildInt; 
} 

public String toString(){ 
    return new JSONObject(this).toString(); 
} 

public String toStringParent(){ 
    return super.toString(); 
} 
} 

결과 :의 toString 아이 : { "attrChildInt": 10, "attrChildString"

아래의 예를 참조하십시오 : "child"} toString 상위 : { "attrChildInt": 10, "attrChildString": "child"}

하지만 부모 값을 표시해야합니다. 예 : { "attrChildInt": 10, "attrChildString": "아이", "이름": "테스트", "수": "5"}

어떤 생각?

감사합니다.

+0

'@ Override' 주석을 추가하여'toString()'메소드가 덮어 쓰기되어 있는지 확인하십시오. – Dragos

답변

0

재미, 내 이클립스에 코드를 복사, 프로젝트에 http://json.org/java에서 소스를 추가, 실행 여기에 내가 무엇을 얻을 :

toString child : {"attrChildInt":10,"name":"test","number":5,"attrChildString":"child"} 
toString Parent : {"attrChildInt":10,"name":"test","number":5,"attrChildString":"child"} 

나는 그러나, 자바 6에있어 및

+0

apache-tomcat-7.0.20 \ lib \ json-20080701.jar (http://www.jarfinder.com/index.php/jars/versionInfo/21653)를 사용 중입니다. 나는 Gson을 사용하여이 코드를 시도했다.이 https://github.com/douglascrockford/JSON-java/zipball/master와 2 개의 옵션이 잘 동작했다. 문제는 심지어 20080701.jar 여야합니다. 답변 해 주셔서 감사합니다. – vctlzac

1

분명히 수퍼 클래스가 아닌 객체에 정의 된 필드를 사용합니다. 그냥 다른 databilding 도구 잡아 (그들의 톤이 - 예를 GSON, XStream을위한을, 내 자신의 databiding :. https://github.com/ko5tik/jsonserializer가)

0

this implementation of JSONObject이 질문의 시점에서 진정한되어 있어야 사용, 그들은 분명히 이후 버전에서이 버그를 해결했습니다 . json 20180130을 사용했는데 정상적으로 작동했습니다.