My Use case is I have a json file but I have to share only few of them to client.
Ex: Consider the source json file as shown below.
{
"name": "XYZ",
"age": 24,
"education": {
"college": "ppppp",
"study": "b.tech",
"grade": 6.8
},
"friends": ["kkkk",
"bbbbbbbbbbb",
"jjjjjj"],
"dob":"01-08-1990"
}
For client 1 I have to share below output
{
"personalInfo": {
"name": "XYZ",
"age": 24,
"friendsNames": ["kkkk","bbbbbbbbbbb","jjjjjj"]
},
"educationalInfo": {
"college": "ppppp",
"study": "b.tech",
"grade": 6.8
}
}
For client 2 I have to share below output
{
"personalInformation": {
"nameOfEmployee": "XYZ",
"ageOfEmployee": 24
},
"educationalInformation": {
"college": "ppppp",
"study": "b.tech"
}
}
And for other clients also the use case is same, I have to skip some keys and give different names to the keys. How to dynamically do this by some kind of configuration. I used jsonPath to achieve this but removing few keys from json object is difficult. Any suggestions can be appreciated.
Use a JSON Path library, like JayWay. With that, templates to transform your exapmle would be:
Client 1
{
"personalInfo": {
"name": "$.name",
"age": "$.age",
"friendsNames": "$.friends"
},
"educationalInfo": "$.education"
}
Client 2
{
"personalInformation": {
"nameOfEmployee": "$.name",
"ageOfEmployee": "$.age"
},
"educationalInformation": {
"college": "$.education.college",
"study": "$.education.study"
}
}
What you need to implement is the template traversal. It's about 20 lines of code; or 40 if you also need to transform list elements, like:
{
"friends": [ "$.friends[?(# =~ /.{5,}/)]", {
"name": "#",
"since": "$.dob"
} ]
}
which would result into:
{
"friends": [ {
"name": "bbbbbbbbbbb",
"since": "01-08-1990"
}, {
"name": "jjjjjj",
"since": "01-08-1990"
} ]
}
You can use Jackson to serialize and deserialize json. I suggest you to create seperate classes which represents your client data.
I show you an example of how you can deserialize your data and map it to your client json.
You can generate corresponding classes for client 2 with getting some help from http://www.jsonschema2pojo.org/ for mapping json to pojo.
Here is the code :
public class Main {
public static void main(String[] args) throws ParseException, ParserConfigurationException, IOException, SAXException {
ObjectMapper mapper = new ObjectMapper();
Root root = mapper.readValue(new File("test.json"), Root.class);
Client1 c1 = new Client1();
PersonalInfo personalInfo1 = new PersonalInfo();
personalInfo1.setAge(root.getAge());
personalInfo1.setFriendsNames(root.getFriends());
personalInfo1.setName(root.getName());
EducationalInfo educationalInfo1 = new EducationalInfo();
educationalInfo1.setCollege(root.getEducation().getCollege());
educationalInfo1.setGrade(root.getEducation().getGrade());
educationalInfo1.setStudy(root.getEducation().getStudy());
c1.setPersonalInfo(personalInfo1);
c1.setEducationalInfo(educationalInfo1);
mapper.writeValue(new File("client1.json"), c1);
}
}
Inside test.json file :
{
"name": "XYZ",
"age": 24,
"education": {
"college": "ppppp",
"study": "b.tech",
"grade": 6.8
},
"friends": [
"kkkk",
"bbbbbbbbbbb",
"jjjjjj"
],
"dob": "01-08-1990"
}
Inside client1.json file :
{
"personalInfo": {
"name": "XYZ",
"age": 24,
"friendsNames": [
"kkkk",
"bbbbbbbbbbb",
"jjjjjj"
]
},
"educationalInfo": {
"college": "ppppp",
"study": "b.tech",
"grade": 6.8
}
}
Here is the classes which represents your json data:
class Education {
private String college;
private String study;
private float grade;
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
public String getStudy() {
return study;
}
public void setStudy(String study) {
this.study = study;
}
public float getGrade() {
return grade;
}
public void setGrade(float grade) {
this.grade = grade;
}
}
// root of your base json data
class Root {
private String name;
private int age;
private Education education;
private List<String> friends;
private String dob;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Education getEducation() {
return education;
}
public void setEducation(Education education) {
this.education = education;
}
public List<String> getFriends() {
return friends;
}
public void setFriends(List<String> friends) {
this.friends = friends;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
}
class EducationalInfo {
private String college;
private String study;
private float grade;
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
public String getStudy() {
return study;
}
public void setStudy(String study) {
this.study = study;
}
public float getGrade() {
return grade;
}
public void setGrade(float grade) {
this.grade = grade;
}
}
// class which represents client 1 json data
class Client1 {
private PersonalInfo personalInfo;
private EducationalInfo educationalInfo;
public PersonalInfo getPersonalInfo() {
return personalInfo;
}
public void setPersonalInfo(PersonalInfo personalInfo) {
this.personalInfo = personalInfo;
}
public EducationalInfo getEducationalInfo() {
return educationalInfo;
}
public void setEducationalInfo(EducationalInfo educationalInfo) {
this.educationalInfo = educationalInfo;
}
}
class PersonalInfo {
private String name;
private int age;
private List<String> friendsNames = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getFriendsNames() {
return friendsNames;
}
public void setFriendsNames(List<String> friendsNames) {
this.friendsNames = friendsNames;
}
}
What about converting it to XML then create some XSLT? it might be much readable and cleaner.
I push full worked example in java into GIT with libs (lombok and jackson)
Template json mapped to object and object to json with different clients.
Your job is to output multilevel JSON data as multiple JSON formats. JSONPath can do this but the process is a hassle.
A simple alternative is to use SPL. SPL is a Java open-source package. You just need three lines of code to get the job done:
enter image description here
SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as jsonparse.splx and invoke it in a Java application as you call a stored procedure:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st = con.prepareCall("call jsonparse()");
st.execute();
…
Java doesn't have great templating built in.
But if you want to do a quick an dirty JSON template where you can replace a few values -- especially without all that ugly quote escaping:
{"key":"value"}
You can use single quotes and string replace:
{'key':'VALUE'}.replace("'", """).replace("VALUE", 42)
A few caveats:
This will break if any existing keys or values have single quotes (like O'malley).
It won't replace strings with numbers, boolean, or null
It can't -- by itself -- insert nested arrays or objects (e.g. [] {}) other than as strings.
But with a little bit of of extra work, you can accomplish the 80/20 rule. After that point you'd probably want to look into parsing or generating -- but by then you're not looking for a quick template.
Related
Hi i want to convert this json to json object in java so that i can pass it to http request to call an api
{
"aliasNaming": true,
"dataServiceType": "BROWSE",
"deviceName": "MyDevice",
"langPref": " ",
"maxPageSize": "2000",
"outputType": "VERSION1",
"password": "!jshjhsdhshdj",
"query": {
"autoClear": true,
"autoFind": true,
"condition": [
{
"controlId": "F4211.CO",
"operator": "EQUAL",
"value": [
{
"content": "00098",
"specialValueId": "LITERAL"
}
]
},
{
"controlId": "F4211.DCTO",
"operator": "EQUAL",
"value": [
{
"content": "SM",
"specialValueId": "LITERAL"
}
]
},
{
"controlId": "F4211.UPMJ",
"operator": "GREATER_EQUAL",
"value": [
{
"content": "01/01/17",
"specialValueId": "LITERAL"
}
]
}
],
"matchType": "MATCH_ALL"
},
"returnControlIDs": "F4211.DOCO|F4211.TRDJ|F4211.CRCD|F4211.AN8|F4211.DSC2|F4211.DSC1|F4211.LITM|F4211.LOTN|F4211.UORG|F4211.UPRC|F4211.AEXP",
"targetName": "F4211",
"targetType": "table",
"token": "044biPNadxNVGhyAKdrImoniK98OOa2l86ZA63qCr4gE5o=MDIwMDA4LTIyNDU5MjUxMTY2MzY3NTA3MTRNeURldmljZTE1Mzc0MjYwMjAyNTk=",
"username": "Ali"
}
i have created 4 models using http://www.jsonschema2pojo.org.
those models just have getter setter in it. look something like this
#JsonProperty("aliasNaming")
private Boolean aliasNaming;
#JsonProperty("dataServiceType")
private String dataServiceType;
#JsonProperty("deviceName")
private String deviceName;
#JsonProperty("langPref")
private String langPref;
#JsonProperty("maxPageSize")
private String maxPageSize;
#JsonProperty("outputType")
private String outputType;
#JsonProperty("password")
private String password;
#JsonProperty("query")
private Query query;
#JsonProperty("returnControlIDs")
private String returnControlIDs;
#JsonProperty("targetName")
private String targetName;
#JsonProperty("targetType")
private String targetType;
#JsonProperty("token")
private String token;
#JsonProperty("username")
private String username;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("aliasNaming")
public Boolean getAliasNaming() {
return aliasNaming;
}
#JsonProperty("aliasNaming")
public void setAliasNaming(Boolean aliasNaming) {
this.aliasNaming = aliasNaming;
}
#JsonProperty("dataServiceType")
public String getDataServiceType() {
return dataServiceType;
}
#JsonProperty("dataServiceType")
public void setDataServiceType(String dataServiceType) {
this.dataServiceType = dataServiceType;
}
#JsonProperty("deviceName")
public String getDeviceName() {
return deviceName;
}
#JsonProperty("deviceName")
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
#JsonProperty("langPref")
public String getLangPref() {
return langPref;
}
#JsonProperty("langPref")
public void setLangPref(String langPref) {
this.langPref = langPref;
}
#JsonProperty("maxPageSize")
public String getMaxPageSize() {
return maxPageSize;
}
#JsonProperty("maxPageSize")
public void setMaxPageSize(String maxPageSize) {
this.maxPageSize = maxPageSize;
}
#JsonProperty("outputType")
public String getOutputType() {
return outputType;
}
#JsonProperty("outputType")
public void setOutputType(String outputType) {
this.outputType = outputType;
}
#JsonProperty("password")
public String getPassword() {
return password;
}
#JsonProperty("password")
public void setPassword(String password) {
this.password = password;
}
#JsonProperty("query")
public Query getQuery() {
return query;
}
#JsonProperty("query")
public void setQuery(Query query) {
this.query = query;
}
#JsonProperty("returnControlIDs")
public String getReturnControlIDs() {
return returnControlIDs;
}
#JsonProperty("returnControlIDs")
public void setReturnControlIDs(String returnControlIDs) {
this.returnControlIDs = returnControlIDs;
}
#JsonProperty("targetName")
public String getTargetName() {
return targetName;
}
#JsonProperty("targetName")
public void setTargetName(String targetName) {
this.targetName = targetName;
}
#JsonProperty("targetType")
public String getTargetType() {
return targetType;
}
#JsonProperty("targetType")
public void setTargetType(String targetType) {
this.targetType = targetType;
}
#JsonProperty("token")
public String getToken() {
return token;
}
#JsonProperty("token")
public void setToken(String token) {
this.token = token;
}
#JsonProperty("username")
public String getUsername() {
return username;
}
#JsonProperty("username")
public void setUsername(String username) {
this.username = username;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
Now i want to set the values in these models by creating their respective objects and finally i got one main object with all the data. like this
Value Vobj1 = new Value();
Vobj1.setContent("00098");
Vobj1.setSpecialValueId("LITERAL");
List<Value> valueList1= new ArrayList<Value>();
valueList1.add(Vobj1);
Value Vobj2 = new Value();
Vobj2.setContent("SM");
Vobj2.setSpecialValueId("LITERAL");
List<Value> valueList2= new ArrayList<Value>();
valueList2.add(Vobj2);
Value Vobj3 = new Value();
Vobj3.setContent("01/01/17");
Vobj3.setSpecialValueId("LITERAL");
List<Value> valueList3= new ArrayList<Value>();
valueList3.add(Vobj3);
Condition Cobj1 = new Condition();
Cobj1.setControlId("F4211.CO");
Cobj1.setOperator("EQUAL");
Cobj1.setValue(valueList1);
Condition Cobj2 = new Condition();
Cobj2.setControlId("F4211.DCTO");
Cobj2.setOperator("EQUAL");
Cobj2.setValue(valueList1);
Condition Cobj3 = new Condition();
Cobj3.setControlId("F4211.UPMJ");
Cobj3.setOperator("GREATER_EQUAL");
Cobj3.setValue(valueList1);
List<Condition> conditionList1 = new ArrayList<Condition>();
conditionList1.add(Cobj1);
conditionList1.add(Cobj2);
conditionList1.add(Cobj3);
Query Qobj1= new Query();
Qobj1.setAutoClear(true);
Qobj1.setAutoFind(true);
Qobj1.setCondition(conditionList1);
Qobj1.setMatchType("MATCH_ALL");
JSONStructure obj=new JSONStructure();
obj.setAliasNaming(true);
obj.setDataServiceType("BROWSE");
obj.setDeviceName("MyDevice");
obj.setLangPref(" ");
obj.setMaxPageSize("2000");
obj.setOutputType("VERSION1");
obj.setPassword("!J0g3t6000");
obj.setQuery(Qobj1);
obj.setReturnControlIDs("F4211.DOCO|F4211.TRDJ|F4211.CRCD|F4211.AN8|F4211.DSC2|F4211.DSC1|F4211.LITM|F4211.LOTN|F4211.UORG|F4211.UPRC|F4211.AEXP");
obj.setTargetName("F4211");
obj.setTargetType("table");
obj.setToken(Token);
obj.setUsername("JOGET");
Now obj is my final object that i am going to pass to an http request and call the api and get the data from it. i want to make sure that my json is created correct, how am i suppose to print the all the data inside this object? and am i going correct with this approach?
if you use maven put gson into your pom.xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
then print your object like this
System.out.println(new Gson().toJson(yourObj));
your object will print in json
I found two full working examples that is familiar with your case.
1) Using Gson refer to the tutorial Parse json string and java object into Gson tree model
2) Using Jackson refer to the tutorial Convert Java Object to/from JSON using JACKSON API
Hope this help.
I have below response for one of my web service and I'm using Retrofit and GSON.
{
"error": false,
"Timeline": {
"Date": "2040-06-15",
"bandList": {
"breakfast": {
"dosageList": {
"01": {
"packed": "true",
"medicineList": [
{
"medicine": {
"id": "01",
"name": "glipizide 5 mg tablet, 100 ",
"category": "regular",
"image": null,
"indication": "NIDDM",
"packed": true,
"med_id": "352",
"dosage": 1
}
},
{
"medicine": {
"id": "04",
"name": "Frusemide (Terry White Chemists) 20 mg uncoated tablet, 100 ",
"category": "regular",
"image": null,
"indication": "Fluid",
"packed": true,
"med_id": "4",
"dosage": 2
}
}
]
},
"02": {
"packed": "false",
"medicineList": [
{
"medicine": {
"id": "05",
"name": "Refresh Tears Plus 0.5% eye drops solution, 15 mL ",
"category": "regular",
"image": null,
"indication": "Dry Eyes",
"packed": false,
"med_id": "372",
"dosage": 1
}
}
]
}
}
}
}
}
}
Q1.
Is there a way to parse above response using model classes (POJOs) or without them? I'm stuck at generating model classes for above structure. How do I generate POJOs for above JSON?
Q2. I'm in a position how to convince to send below response, what is the correct structure/format for JSON? Is there any JSON standard I could show to the web developer to get this JSON format? (note:I'm okay to parse this structure)
{
"error": false,
"Timeline": {
"Date": "2040-06-15",
"band": [
{
"name": "breakfast",
"dosage": [
{
"id": "01",
"packed": "true",
"medicine": [
{
"id": "01",
"name": "glipizide 5 mg tablet, 100 ",
"category": "regular",
"image": null,
"indication": "NIDDM",
"packed": true,
"med_id": "52",
"dosage": 1
},
{
"id": "04",
"name": "Frusemide (Terry White Chemists) 20 mg uncoated tablet, 100 ",
"category": "regular",
"image": null,
"indication": "Fluid",
"packed": true,
"med_id": "54",
"dosage": 2
}
]
},
{
"id": "02",
"packed": "false",
"medicine": [
{
"id": "05",
"name": "Refresh Tears Plus 0.5% eye drops solution, 15 mL ",
"category": "regular",
"image": null,
"indication": "Dry Eyes",
"packed": false,
"med_id": "372",
"dosage": 1
}
]
}
]
}
]
}
}
Thank you in advance.
EDIT
I use to autogenerate POJOs using those sites, but its giving below responses for some classes. How do I convert this to proper class?
package ;
public class DosageList
{
private 01 01;
private 02 02;
public void set01(01 01){
this.01 = 01;
}
public 01 get01(){
return this.01;
}
public void set02(02 02){
this.02 = 02;
}
public 02 get02(){
return this.02;
}
}
EDIT 2
I have almost done parsing first JSON, but stuck in here.
for (String bandName: event.getTimeline().getBand().keySet()) {
Log.d("<<<--Band-->>>", "Value " + event.getTimeline().getBand().get(bandName));
Band band = event.getTimeline().getBand().get(bandName);
for (String dosageName:band.getDosage().keySet()) {
Dosage dosage = band.getDosage().get(dosageName);
Log.d("<<<--Dosage-->>>", "Value " + dosage.getMedicine());
for (Medicine medicine: dosage.getMedicine()) {
Log.d("<<<--Medicine-->>>", "Value " + dosage.getMedicine().get(0));
}
}
}
How do I retrieve medicine values?
public class Medicine
{
private String id;
private String name;
private String category;
private String image;
private String indication;
private boolean packed;
private String med_id;
private int dosage;
public void setId(String id){
this.id = id;
}
public String getId(){
return this.id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setCategory(String category){
this.category = category;
}
public String getCategory(){
return this.category;
}
public void setImage(String image){
this.image = image;
}
public String getImage(){
return this.image;
}
public void setIndication(String indication){
this.indication = indication;
}
public String getIndication(){
return this.indication;
}
public void setPacked(boolean packed){
this.packed = packed;
}
public boolean getPacked(){
return this.packed;
}
public void setMed_id(String med_id){
this.med_id = med_id;
}
public String getMed_id(){
return this.med_id;
}
public void setDosage(int dosage){
this.dosage = dosage;
}
public int getDosage(){
return this.dosage;
}
}
import java.util.ArrayList;
import java.util.List;
public class Dosage
{
private String id;
private String packed;
private List<Medicine> medicine;
public void setId(String id){
this.id = id;
}
public String getId(){
return this.id;
}
public void setPacked(String packed){
this.packed = packed;
}
public String getPacked(){
return this.packed;
}
public void setMedicine(List<Medicine> medicine){
this.medicine = medicine;
}
public List<Medicine> getMedicine(){
return this.medicine;
}
}
import java.util.ArrayList;
import java.util.List;
public class Band
{
private String name;
private List<Dosage> dosage;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setDosage(List<Dosage> dosage){
this.dosage = dosage;
}
public List<Dosage> getDosage(){
return this.dosage;
}
}
import java.util.ArrayList;
import java.util.List;
public class Timeline
{
private DateTime Date;
private List<Band> band;
public void setDate(DateTime Date){
this.Date = Date;
}
public DateTime getDate(){
return this.Date;
}
public void setBand(List<Band> band){
this.band = band;
}
public List<Band> getBand(){
return this.band;
}
}
public class Root
{
private boolean error;
private Timeline Timeline;
public void setError(boolean error){
this.error = error;
}
public boolean getError(){
return this.error;
}
public void setTimeline(Timeline Timeline){
this.Timeline = Timeline;
}
public Timeline getTimeline(){
return this.Timeline;
}
}
...enjoy...
For first question:
You can parse JSON without POJO classes but it is recommended to use
them and About you are stucking about generating them from the JSON
you can use jsonschema2pojo I think
it is the best.
And for the second one:
Yest there are standards for JSON you can find them in JSON website.
Step 1 : First start with the inner most json object which I can see is "medicine"
Create a POJO class something like this
public class Medicine implements android.os.Parcelable {
#SerializedName("id")
private String id;
// Getter setter method for id
// Do it for all the JSON tags
}
Step 2 : Create a class for "medicineList" this will somewhat be like this
public class MedicineList implements Parcelable {
#SerializedName("medicineList")
private List<Medicine > medicine;
// Getter setter can go here
}
In the similar fashion just move outside to your base tag in JSON response. This make things pretty easy for me to understand. I am not posting to the complete solution as thats your homework at EOD.
the solution for Q1 -
Yes, you can parse above response using model classes by installing the DTO plugin in the Android Studio. The plugin will automatically create the POJO class for the response.
I am trying to read some values under "properties" of following JSON string to a POJO. But all I get is null values.
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
144.9798,
-37.743
]
},
"properties": {
"PFI": "51351644",
"EZI_ADD": "581 BELL STREET COBURG 3058",
"ROAD_NAME": "BELL",
"ROAD_TYPE": "STREET",
"LOCALITY": "COBURG",
"LGA_CODE": "316",
"STATE": "VIC",
"POSTCODE": "3058",
"ADD_CLASS": "S"
},
"id": "ADDRESS.581"
}
My POJO class
#JsonIgnoreProperties(ignoreUnknown = true)
class Property {
public Property(){}
private String EZI_ADD; // e.g., "14 FAIRWAY COURT BUNDOORA 3083"
private String STATE; // e.g., "VIC"
private String POSTCODE; // e.g., "3083"
private String LGA_CODE; // e.g., 373
private String LOCALITY; // e.g., "BUNDOORA"
private String ADD_CLASS; // e.g., "S", or "M"
private String SA1_7DIG11 = ""; // SA1 code e.g., "2120241"
public String getEZI_ADD() {
return EZI_ADD;
}
#JsonProperty("EZI_ADD")
public void setEZI_ADD(String eZI_ADD) {
EZI_ADD = eZI_ADD;
}
public String getSTATE() {
return STATE;
}
#JsonProperty("STATE")
public void setSTATE(String sTATE) {
STATE = sTATE;
}
public String getPOSTCODE() {
return POSTCODE;
}
#JsonProperty("POSTCODE")
public void setPOSTCODE(String pOSTCODE) {
POSTCODE = pOSTCODE;
}
public String getLGA_CODE() {
return LGA_CODE;
}
#JsonProperty("LGA_CODE")
public void setLGA_CODE(String lGA_CODE) {
LGA_CODE = lGA_CODE;
}
public String getLOCALITY() {
return LOCALITY;
}
#JsonProperty("LOCALITY")
public void setLOCALITY(String lOCALITY) {
LOCALITY = lOCALITY;
}
public String getADD_CLASS() {
return ADD_CLASS;
}
#JsonProperty("ADD_CLASS")
public void setADD_CLASS(String aDD_CLASS) {
ADD_CLASS = aDD_CLASS;
}
public String getSA1_7DIG11() {
return SA1_7DIG11;
}
#JsonProperty("SA1_7DIG11")
public void setSA1_7DIG11(String sA1_7DIG11) {
SA1_7DIG11 = sA1_7DIG11;
}
}
Conversion code is as follows
//Above json string
String jsonString = "{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[144.9798,-37.743]},\"properties\":{\"PFI\":\"51351644\",\"EZI_ADD\":\"581 BELL STREET COBURG 3058\",\"ROAD_NAME\":\"BELL\",\"ROAD_TYPE\":\"STREET\",\"LOCALITY\":\"COBURG\",\"LGA_CODE\":\"316\",\"STATE\":\"VIC\",\"POSTCODE\":\"3058\",\"ADD_CLASS\":\"S\"},\"id\":\"ADDRESS.581\"}";
ObjectMapper mapper = new ObjectMapper();
Property properties = mapper.readValue(jsonString, Property.class);
Output:
{
"properties": {
"EZI_ADD": null,
"STATE": null,
"POSTCODE": null,
"LGA_CODE": null,
"LOCALITY": null,
"ADD_CLASS": null,
"SA1_7DIG11": ""
}
}
The JSON String you're sending does not match the Property class. Add a wrapper class, e.g. something like this:
public class Feature {
private String type;
private String id;
private Property property;
// getters and setters
}
Then you can send the request and the JSON String will be parsed to your object:
{
"type": "feature",
"id": "test",
"property": {
"PFI": "51351644",
"EZI_ADD": "581 BELL STREET COBURG 3058",
"ROAD_NAME": "BELL",
"ROAD_TYPE": "STREET",
"LOCALITY": "COBURG",
"LGA_CODE": "316",
"STATE": "VIC",
"POSTCODE": "3058",
"ADD_CLASS": "S"
}
}
I need to deserialize the following:
{
"name": "library",
"contains": [
{
"name: "office",
"contains": []
},
{
"name": "Home",
"contains":[{
"name": "Shelf",
"contains" : []
}]
}]
}
My class looks like this:
public class Container
{
String containerName;
}
Public class Contains extends Container {
#SerializedName("contains")
#Expose
private List<Container> contains;
}
How is it that when I run my code, I am hoping to get a contains object to run my methods it won't get me them. But I get a container object and can't run my methods from within my Contains class.
You don't need inheritance here. Just use Gson.fromJson().
Object class
public class Container {
#SerializedName("name")
#Expose
private String name;
#SerializedName("contains")
#Expose
private List<Container> contains;
public Container(String name) {
this.name = name;
contains = new ArrayList<Container>();
}
public void setName(String name) {
this.name = name;
}
public void add(Container c) {
this.contains.add(c);
}
public void setContainerList(List<Container> contains) {
this.contains = contains;
}
public String getName() {
return name;
}
public List<Container> getContainerList() {
return this.contains;
}
}
Code
public static void main(String[] args) {
Container lib = new Container("library");
Container office = new Container("office");
Container home = new Container("Home");
Container shelf = new Container("Shelf");
home.add(shelf);
lib.add(office);
lib.add(home);
Gson gson = new Gson();
// Serialize
String json = gson.toJson(lib);
// Deserialize
Container container = gson.fromJson(json, Container.class);
System.out.println(container.getName());
for (Container c : container.getContainerList()) {
System.out.println("-- " + c.getName());
}
}
Output
library
-- office
-- Home
I have two files: occupations.json and people.json. The former is just an array of occupations:
[
{ "name": "director", "pay": "100000"},
{ "name": "programmer", "pay": "75000"},
{ "name": "teacher", "pay": "50000"}
]
And the latter an array of a few people along with their occupation:
[
{ "name": "Mary", "occupation": "programmer" },
{ "name": "Jane", "occupation": "director" },
{ "name": "John", "occupation": "teacher" }
]
And these are the corresponding classes:
public class Occupation {
private final String name;
private final int pay;
public String getName() { ... }
public int getPay() { ... }
}
public class Person {
private final String name;
private final Occupation occupation;
public String getName() { ... }
public String getOccupation() { ... }
}
Currently I'm using ObjectMapper.readValue(InputStream, Class) to
unserialize the files. How can I make Person class aware of all existing Occupation objects? I want to select which occupation a person has by using the occupation's name.
add a function to Person.class
public Occupation getOccupation_()
{
// assume you had a static occupations list...
for (Occupation o : occupations)
if (o.name == this.occupation)
return o;
return null;
}