如何将下面的 json 字符串转换为 java 对象?

我想把下面的 JSON 字符串转换成一个 java 对象:

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"
}
]
}"

我的目标是很容易地访问它,比如:

(e.g. MyJsonObject myobj = new MyJsonObject(jsonString)
myobj.mymusic[0].id would give me the ID, myobj.libraryname gives me "My Library").

我听说过 Jackson,但我不确定如何使用它来适应我的 json 字符串,因为它不仅仅是键值对,由于“ mymusic”列表涉及。如果杰克逊不是最佳人选,我怎么才能和杰克逊一起完成呢? 还是有更简单的方法?

518766 次浏览

Gson 也很适合它: 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 更多例子: < a href = “ http://www.mkyong.com/java/how-do-turn-java-object-to-from-json-format-gson-api/”rel = “ nofollow”> http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

看看 Google 的 Gson: http://code.google.com/p/google-gson/

来自他们的网站:

Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

您只需要使用 json 字符串中的所有字段创建一个 MyType 类(当然是重命名的)。如果您喜欢手动执行所有的解析(也非常简单) ,那么在执行数组时可能会变得有点复杂,请查看 http://www.json.org/并下载 Json 解析器对象的 Java 源代码。

不需要使用 GSON; Jackson 可以做任意一个简单的地图/列表:

ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);

或者更方便的 JSON 树:

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

下划线-java (我就是开发者)可以将 json 转换为 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 + "]";
}

在我的示例中,我将 JSON 字符串作为列表传递。因此,当您传递列表时,请使用下面的解决方案。

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>>>(){});