将json部分反序列化为POJO,但保留一些原始json作为字段

时间:2017-11-17 09:21:36

标签: java android json gson

我有一个json如下:

"customer": {  
     "personal": {  
        "name": “jim johnson”,  
        “miscellaneous”: {  
            “active”: “true”,  
            “addons”: {  
              "location": “us”  
            },  
        “customer_id”: “1234”   
        }    
    },  
    “source”: “main db”  
}  

我可以一对一地创建一个简单的POJO映射,但我想要的是以下内容:
我想有一个如下的对象:

class Customer {  
   Personal personal;  
   String source;  
}   

class Personal {  
    String name;
    String customer_id;  
    String miscellaneous; // <—— This is the problem  
    // JsonObject miscellaneous;
}    

如何反序列化json并将miscellaneous保存为原始json字符串?或者甚至把它作为原始的json元素?

3 个答案:

答案 0 :(得分:0)

public class myClassName {
        public Customer customer;
        public class Customer {
            public Personal personal;
            public String source;
        }
        public class Personal {
            public String name;
           public Miscellaneous miscellaneous;
        }
        public class Miscellaneous {
            public String active;
           public Addons addons;
                   public String customerId;
        }
        public class Addons {
            public String location;
        }
    }

答案 1 :(得分:0)

因为,根据您的JSON miscellaneous并非String

    “miscellaneous”: {  
        “active”: “true”,  
        “addons”: {  
          "location": “us”  
        },  
    “customer_id”: “1234”   
    } 

您需要编写一个类并声明miscellaneous

所需的属性
   public class Miscellaneous {
       private boolean active;
       private Addons addons;
       private String customerId;
     // getter and setter
    }

然后

String miscellaneous;

应该改为

Miscellaneous miscellaneous;

答案 2 :(得分:0)

您可以将miscellaneous属性设置为JTokenNewtonsoft.Json.Linq),而不是String

JToken miscellaneous;

反序列化后,您可以访问miscellaneous.ToString()以获取以下值作为原始JSON字符串。

{  
    "active": "true",
    "addons": {
        "location": "us"
    },
    "customer_id": "1234"   
}

我觉得这篇文章有点陈旧,但我希望它可以帮助任何人绊倒它。