有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中将json数据字符串转换为字典数组

我有一个装满字典数组的数组。我将这个数组作为字符串发送到一个mysql数据库进行存储和检索。数组的数量和字典的数量因每个条目而异。在objective-C中,这非常简单,我使用这段代码将数组转换为字符串

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:itemListArray options:kNilOptions error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

NSData *td = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *newArray = [NSJSONSerialization JSONObjectWithData:td options:kNilOptions error:&error];

这对于填充我的表视图和访问详细信息所需的数据非常有用

我被困在如何在java中实现这一点上。下面是从webservice接收的字符串示例

[[{"Person":"Me","PersonID":0,"Description":"jake"},{"Person":"Me","PersonID":0,"Description":"mickey"}],[{"Person":"You","PersonID":1,"Description":"sophia"},{"Person":"You","PersonID":1,"Description":"jasmine"}]]

如您所见,它是一个二维数组,每个数组有两个数组和两个字典。如何将其转换为java中的字典数组?我尝试过这样的方法,其中ed2是一个字符串,如上图所示

JSONArray jArray = new JSONArray(ed2);
JSONObject jObject = new JSONObject(ed2);

但这两种方法都会抛出异常,并且不会编译。对java来说真的很陌生,但我看到的每一个接近的例子都使用了这些对象。如果有一个类似于objective-c的函数来简化我似乎找不到的内容,那就太棒了,但如果需要的话,我总是可以解析字符串并用蛮力填充数组

编辑: 下面是解决问题的代码片段

// JSONArray from server, pull out the first object in the array
JSONObject jsonObject = (JSONObject) getItem(position);
if (jsonObject.has("EventData")) {
      eventData = jsonObject.optString("EventData");
}
// clean up some aspects of the string (this will be fixed later, extra characters will not be stored. 
String ed2 = (eventData.replace("\\", ""));
    // ed2 at this point: [[{"Person":"Me","PersonID":0,"Description":"jake"},{"Person":"Me","PersonID":0,"Description":"mickey"}],[{"Person":"You”,"PersonID":1,"Description":"sophia"},{"Person":"You”,"PersonID":1,"Description":"jasmine"}]]
try {
    JSONArray jArray = new JSONArray(ed2);
} catch (JSONException e) {
    e.printStackTrace();
    // error: Method threw 'java.lang.NullPointerException' exception. Cannot evaluate org.json.JSONArray.toString()
}
try {
    JSONObject jObject = new JSONObject(ed2);
} catch (JSONException e) {
    e.printStackTrace();
    // error: Method threw 'java.lang.NullPointerException' exception. Cannot evaluate org.json.JSONObject.toString() 
}

共 (0) 个答案