I want to convert the following JSON string to a java object:
String jsonString = "{
"libraryname": "My Library",
"mymusic": [
{
"Artist Name": "Aaron",
"Song Name": "Beautiful"
},
{
"Artist Name": "Britney",
"Song Name": "Oops I did It Again"
},
{
"Artist Name": "Britney",
"Song Name": "Stronger"
}
]
}"
My goal is to access it easily something like:
(e.g. MyJsonObject myobj = new MyJsonObject(jsonString)
myobj.mymusic[0].id would give me the ID, myobj.libraryname gives me "My Library").
I've heard of Jackson, but I am unsure how to use it to fit the json string I have since its not just key value pairs due to the "mymusic" list involved. How can I accomplish this with Jackson or is there some easier way I can accomplish this if Jackson is not the best for this?
No need to go with GSON for this; Jackson can do either plain Maps/Lists:
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);
or more convenient JSON Tree:
JsonNode rootNode = mapper.readTree(json);
By the way, there is no reason why you could not actually create Java classes and do it (IMO) more conveniently:
public class Library {
@JsonProperty("libraryname")
public String name;
@JsonProperty("mymusic")
public List<Song> songs;
}
public class Song {
@JsonProperty("Artist Name") public String artistName;
@JsonProperty("Song Name") public String songName;
}
Library lib = mapper.readValue(jsonString, Library.class);
Check out Google's Gson: http://code.google.com/p/google-gson/
From their website:
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
You would just need to make a MyType class (renamed, of course) with all the fields in the json string. It might get a little more complicated when you're doing the arrays, if you prefer to do all of the parsing manually (also pretty easy) check out http://www.json.org/ and download the Java source for the Json parser objects.
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(response);// response will be the json String
YourPojo emp = gson.fromJson(object, YourPojo.class);
Gson is also good for it: http://code.google.com/p/google-gson/
" Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. "
Check the API examples:https://sites.google.com/site/gson/gson-user-guide#TOC-Overview More examples: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
Underscore-java can convert json to Object.
String jsonString = "{\n" +
" \"libraryname\":\"My Library\",\n" +
" \"mymusic\":[{\"Artist Name\":\"Aaron\",\"Song Name\":\"Beautiful\"},\n" +
" {\"Artist Name\":\"Britney\",\"Song Name\":\"Oops I did It Again\"},\n" +
" {\"Artist Name\":\"Britney\",\"Song Name\":\"Stronger\"}]}";
Map<String, Object> jsonObject = U.fromJsonMap(jsonString);
System.out.println(jsonObject);
// {libraryname=My Library, mymusic=[{Artist Name=Aaron, Song Name=Beautiful}, {Artist Name=Britney, Song Name=Oops I did It Again}, {Artist Name=Britney, Song Name=Stronger}]}
System.out.println(U.<String>get(jsonObject, "mymusic[0].Artist Name"));
// Aaron
Underscore-java ( which I am the developer of ) can convert json to Object.
import com.github.underscore.U;
String jsonString = "{\n" +
" \"libraryname\":\"My Library\",\n" +
" \"mymusic\":[{\"Artist Name\":\"Aaron\",\"Song Name\":\"Beautiful\"},\n" +
" {\"Artist Name\":\"Britney\",\"Song Name\":\"Oops I did It Again\"},\n" +
" {\"Artist Name\":\"Britney\",\"Song Name\":\"Stronger\"}]}";
Map<String, Object> jsonObject = U.fromJsonMap(jsonString);
System.out.println(jsonObject);
// {libraryname=My Library, mymusic=[{Artist Name=Aaron, Song Name=Beautiful}, {Artist Name=Britney, Song Name=Oops I did It Again}, {Artist Name=Britney, Song Name=Stronger}]}
System.out.println(U.<String>get(jsonObject, "mymusic[0].Artist Name"));
// Aaron
public void parseEmployeeObject() throws NoSuchFieldException, SecurityException, JsonParseException, JsonMappingException, IOException {
Gson gson = new Gson();
ObjectMapper mapper = new ObjectMapper();
// convert JSON string to Book object
Object obj = mapper.readValue(Paths.get("src/main/resources/file.json").toFile(), Object.class);
endpoint = this.endpointUrl;
String jsonInString = new Gson().toJson(obj);
JsonRootPojo organisation = gson.fromJson(jsonInString, JsonRootPojo.class);
for(JsonFilter jfil : organisation.getSchedule().getTradeQuery().getFilter())
{
String name = jfil.getName();
String value = jfil.getValue();
}
System.out.println(organisation);
}
{ "schedule": { "cron": "30 19 2 MON-FRI", "timezone": "Europe/London",
"tradeQuery": { "filter": [ { "name": "bookType", "operand": "equals", "value": "FO" }, { "name": "bookType", "operand": "equals", "value": "FO" } ], "parameter": [ { "name": "format", "value": "CSV" }, { "name": "pagesize", "value": "1000" } ] }, "xslt":"" }
}
public class JesonSchedulePojo {
public String cron;
public String timezone;
public JsonTradeQuery tradeQuery;
public String xslt;
public String getCron() {
return cron;
}
public void setCron(String cron) {
this.cron = cron;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public JsonTradeQuery getTradeQuery() {
return tradeQuery;
}
public void setTradeQuery(JsonTradeQuery tradeQuery) {
this.tradeQuery = tradeQuery;
}
public String getXslt() {
return xslt;
}
public void setXslt(String xslt) {
this.xslt = xslt;
}
@Override
public String toString() {
return "JesonSchedulePojo [cron=" + cron + ", timezone=" + timezone + ", tradeQuery=" + tradeQuery
+ ", xslt=" + xslt + "]";
}
public class JsonTradeQuery {
public ArrayList<JsonFilter> filter;
public ArrayList<JsonParameter> parameter;
public ArrayList<JsonFilter> getFilter() {
return filter;
}
public void setFilter(ArrayList<JsonFilter> filter) {
this.filter = filter;
}
public ArrayList<JsonParameter> getParameter() {
return parameter;
}
public void setParameter(ArrayList<JsonParameter> parameter) {
this.parameter = parameter;
}
@Override
public String toString() {
return "JsonTradeQuery [filter=" + filter + ", parameter=" + parameter + "]";
}
public class JsonFilter {
public String name;
public String operand;
public String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOperand() {
return operand;
}
public void setOperand(String operand) {
this.operand = operand;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "JsonFilter [name=" + name + ", operand=" + operand + ", value=" + value + "]";
}
public class JsonParameter {
public String name;
public String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "JsonParameter [name=" + name + ", value=" + value + "]";
}
public class JsonRootPojo {
public JesonSchedulePojo schedule;
public JesonSchedulePojo getSchedule() {
return schedule;
}
public void setSchedule(JesonSchedulePojo schedule) {
this.schedule = schedule;
}
@Override
public String toString() {
return "JsonRootPojo [schedule=" + schedule + "]";
}
In my case, I passed the JSON string as a list. So use the below solution when you pass the list.
ObjectMapper mapper = new ObjectMapper();
String json = "[{\"classifier\":\"M\",\"results\":[{\"opened\":false}]}]";
List<Map<String, Object>> map = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>(){});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.