Java:JSONObject继承

标签 java json inheritance

我在 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/

相关文章:

java - Sonar 插件与独立 Sonar 和质量概况

c# - 反序列化 json 数组以列出 wp7

c++ - 具有多个签名的函数,尝试调用私有(private)子类而不是更通用的函数

c++ - 避免菱形继承(钻石问题)

java - 如何避免在java中替换文本中的特定单词

java - 设置 spring @cacheable 缓存 10 秒

javascript - 如何制作 .map?

c++ - 指向成员对象的成员指针和声明顺序

java - JAVA 日志记录的最佳方法/性能是什么?字符串或 StringBuilder 或 StringBuffer

javascript - 如何使用 Ajax(没有 jQuery ui)过滤自动建议的 JSON 数据