Reputation: 18786
I have a rather JSON response coming back from a solr instance....
{"responseHeader":
{"status":0,"QTime":1,"params":{"sort":"score asc","fl":"*,score",
"q":"{! score=distance}","wt":"json","fq":"description:motor","rows":"1"}},
"response":{"numFound":9,"start":0,"maxScore":6.8823843,"docs":
[{"workspaceId":2823,"state":"MN","address1":"1313 mockingbird Lane",
"address2":"","url":"http://mydomain.com/","city":"Minneapolis",
"country":"US","id":"399068","guid":"","geo":["45.540239, -98.580473"],
"last_modified":"2012-12-12T20:40:29Z","description":"ELEC MOTOR",
"postal_code":"55555","longitude":"-98.580473","latitude":"45.540239",
"identifier":"1021","_version_":1421216710751420417,"score":0.9288697}]}}
And I'm trying to map that to a java object:
public class Item extends BaseModel implements Serializable {
private static final long serialVersionUID = 1L;
protected Integer workspaceId;
protected String name;
protected String description;
protected String identifier;
protected String identifierSort;
protected Address address;
protected String url;
/** getters and setters eliminated for brevity **/
}
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
protected String address1;
protected String address2;
protected String city;
protected String state;
protected String postalCode;
protected String country;
/** getters and setters eliminated for brevity **/
}
How do I map the address1, address2, city, state, etc... into the Address object in the Item object? I've been reading about Jackson annotations but nothing really jumps out at me as to where to begin.
Upvotes: 2
Views: 1918
Reputation: 18786
We ended up using Solrj - sort of.
We wrote our own SolrResult object that we fed to SolrJ like so:
List<SolrResult> solrResults = rsp.getBeans(SolrResult.class);
And then in SolrResult.java where we had complex or nested objects we just first used SolrJ annotation to get the field and then just set the value as needed...
@Field("address1")
public void setAddress1(String address1) {
this.item.getAddress().setAddress1(address1);
}
It wasn't hard just feels a bit messy, but it does work.
Upvotes: 2
Reputation: 80633
If using Jackson 1.9 or higher you can use the @JsonUnwrapped annotation to handle this.
Here is an example of using it (largely lifted from Jackson's documentation):
public class Name {
private String first, last;
// Constructor, setters, getters
}
public class Parent {
private int age;
@JsonUnwrapped
private Name name;
// Constructor, setters, getters
}
public static void main(String[] args) {
try {
final ObjectMapper mapper = new ObjectMapper();
final Parent parent = mapper.readValue(new File(
"/path/to/json.txt"), Parent.class);
System.out.println(parent);
} catch (final Exception e) {
e.printStackTrace();
}
}
Upvotes: 2