Tôi đã xem tài liệu API cho JSON và dường như không có cách nào để phân tích cú pháp thành chuỗi JSON thành một loại đối tượng cụ thể.
Vì vậy, bạn sẽ chỉ phải tự viết mã để chuyển đổi từng số JSONObject
thành Foo
. Một cái gì đó như thế này nên làm việc:
import grails.converters.JSON
import org.codehaus.groovy.grails.web.json.*
class Foo {
def name
Foo(name) {
this.name = name
}
String toString() {
name
}
}
List list = [new Foo("first"), new Foo("second")]
def jsonString = (list as JSON).toString()
List parsedList = JSON.parse(jsonString)
// Convert from a list of JSONObject to a list of Foo
def foos = parsedList.collect {JSONObject jsonObject ->
new Foo(name: jsonObject.get("name"))
}
Một giải pháp tổng quát hơn sẽ có thêm một parse
phương pháp tĩnh mới như sau vào JSON
metaclass, mà cố gắng để phân tích chuỗi JSON để một danh sách các đối tượng của một đặc biệt loại:
import grails.converters.JSON
import org.codehaus.groovy.grails.web.json.*
class Foo {
def name
Foo(name) {
this.name = name
}
String toString() {
name
}
}
List list = [new Foo("first"), new Foo("second")]
def jsonString = (list as JSON).toString()
List parsedList = JSON.parse(jsonString)
// Define the new method
JSON.metaClass.static.parse = {String json, Class clazz ->
List jsonObjs = JSON.parse(json)
jsonObjs.collect {JSONObject jsonObj ->
// If the user hasn't provided a targetClass read the 'class' proprerty in the JSON to figure out which type to convert to
def targetClass = clazz ?: jsonObj.get('class') as Class
def targetInstance = targetClass.newInstance()
// Set the properties of targetInstance
jsonObj.entrySet().each {entry ->
if (entry.key != "class") {
targetInstance."$entry.key" = entry.value
}
}
targetInstance
}
}
// Try the new parse method
List<Foo> foos = JSON.parse(jsonString, Foo)
// Confirm it worked
assert foos.every {Foo foo -> foo.class == Foo && foo.name in ['first', 'second'] }
Bạn có thể thử mã ở trên trong bảng điều khiển groovy. Một vài cảnh báo
- Tôi đã chỉ thực hiện thử nghiệm rất hạn chế trên mã trên
- Có hai lớp JSON trong mới nhất Grails phát hành, tôi giả sử bạn đang sử dụng một trong đó không bị phản đối
Nguồn
2010-04-20 08:12:53
Có thể tiêm các thuộc tính của mỗi director jsonObj vào trường foo.properties cho mỗi cá thể mới của Foo không? – Armand
@Ali G - Không, tôi nghĩ '.properties' chỉ có thể ghi cho đối tượng miền Grails. Đối với các đối tượng Groovy thông thường, tôi nghĩ '.properties' là chỉ đọc. –
Cảm ơn Don. Cách tiếp cận chung là rất tốt đẹp. – armandino