简体   繁体   English

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

[英]Partially deserialize json into POJO but keep some raw json as field

I have a json as follows: 我有一个json如下:

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

I can create an simple POJO mapping everything one to one but what I would like is the following: 我可以一对一地创建一个简单的POJO映射,但我想要的是以下内容:
I would like to have an object such as follows: 我想有一个如下的对象:

class Customer {  
   Personal personal;  
   String source;  
}   

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

How can I deserialize the json and have the miscellaneous kept as a string of raw json string? 如何反序列化json并将miscellaneous保存为原始json字符串? Or even have it as a raw json element? 或者甚至把它作为原始的json元素?

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;
        }
    }

Because, as per your JSON miscellaneous isn't plain String . 因为,根据你的JSON miscellaneous不是普通的String

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

You need to write a class and declare required property for miscellaneous 你需要写一个类,并申报所需的属性miscellaneous

   public class Miscellaneous {
       private boolean active;
       private Addons addons;
       private String customerId;
     // getter and setter
    }

And, then 接着

String miscellaneous;

should be change to 应该改为

Miscellaneous miscellaneous;

You could set your miscellaneous property to a JToken ( Newtonsoft.Json.Linq ) instead of a String . 您可以将miscellaneous属性设置为JTokenNewtonsoft.Json.Linq )而不是String

JToken miscellaneous;

Once deserialized you could then access miscellaneous.ToString() to get the following value as a raw JSON string. 反序列化后,您可以访问miscellaneous.ToString()以获取以下值作为原始JSON字符串。

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

I see this post is a bit old, but I hope it helps anyone stumbling across it. 我看到这篇文章有点旧,但我希望它可以帮助任何人绊倒它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM