我必须完成另一个程序员的项目,他开始使用Jackson注释和REST apis。我没有经验,现在挣扎了好几个小时。我需要像这样解析json数组:
{
...
"id_s": "3011",
"no_s": "Suteki",
"fl": [
{
"v": "1",
"m": "0",
"id_fs": "243",
"f_c": "2013-08-09 14:43:54",
id_tf": "3",
"u_c": "Aaa",
_u_c": "1347678779",
"c": "Carlos Rojas",
"c_c": "1"
}
]
}
现有的课程如下:
@EBean
@JsonIgnoreProperties(ignoreUnknown = true)
public class Item implements Serializable, MapMarker {
private static final long serialVersionUID = 1L;
@JsonProperty("id_s")
protected int id;
@JsonProperty("id_sucursal")
public void setId_sucursal(int id_sucursal) {
this.id = id_sucursal;
}
@JsonProperty("id_fb")
protected String idFacebook;
@JsonProperty("no_s")
private String name;
...
}
我已阅读here如何解析数组,但如何使用Jackson注释获取 jsonResponseString ?我错过了什么?
谢谢!
答案 0 :(得分:2)
除了遗漏了许多有助于回答你问题的事情之外,我猜你不确定JSON Arrays如何映射到Java对象。如果是这样,它应该是直截了当的:您将JSON数组映射为Java数组或Collection
s(如List
s):
public class Item { // i'll skip getters/setters; can add if you like them
public String id_s;
public String no_s;
public List<Entry> fl;
}
public class Entry {
public String v; // or maybe it's supposed to be 'int'? Can use that
public String m;
public int id_fs; // odd that it's a String in JSON; but can convert
public String f_c; // could be java.util.Date, but Format non-standard (fixable)
// and so on.
}
你要么把JSON读作对象:
ObjectMapper mapper = new ObjectMapper();
Item requestedItem = mapper.readValue(inputStream, Item.class); // or from String, URL etc
// or, write to a stream
OutputStream out = ...;
Item result = ...;
mapper.writeValue(out, result);
// or convert to a String
String jsonAsString = mapper.writeValueAsString(result);
// note, however, that converting to String, then outputting is less efficient
我希望这会有所帮助。
答案 1 :(得分:0)
我之前从未使用过它,但这似乎帮助了其他用户:How can I serialize this JSON using Jackson annotations?
另外,如果可以,为什么不使用Android默认的JSON类?用随机教程搜索:http://www.androidhive.info/2012/01/android-json-parsing-tutorial/