我在 Java 中将对象转换为 JSONObject (org.json.JSONObject) 时遇到问题。
我有一个对象 X,它是子对象 Y。当我创建“new 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 child : {"attrChildInt":10,"attrChildString":"child"} toString 父级:{"attrChildInt":10,"attrChildString":"child"}
但是我需要显示父级的值。 示例: {"attrChildInt":10,"attrChildString":"child","name":"test","number":"5"}
有什么想法吗?
谢谢。
最佳答案
有趣,只需将您的代码复制到我的 Eclipse,添加来自 http://json.org/java 的源代码到项目,执行,这是我得到的:
toString child : {"attrChildInt":10,"name":"test","number":5,"attrChildString":"child"}
toString Parent : {"attrChildInt":10,"name":"test","number":5,"attrChildString":"child"}
我使用 Java 6 并使用 this implementation of JSONObject
关于Java:JSONObject继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8535274/