如何从JSON字符串中获取数据?

时间:2015-10-24 15:27:19

标签: java json

这是我的代码:

try {
    JSONObject json = (JSONObject) new JSONTokener(result).nextValue();
    System.out.println(json);
    JSONObject json2 = json.getJSONObject("data");
    String test = json2.getString("headline");
    System.out.println(test);
} catch (JSONException e) {
    e.printStackTrace();
}

我的字符串值以对象数据开头。所以我首先尝试获取该对象,然后捕获其中的对象标题

我的问题是,它没有从字符串中获取对象数据。 一旦我到达JSONObject json2 = json.getJSONObject("data");行,它就会抛出异常。请详细说明一下。

"data": [
    {
        "headline": "Close Update"
        "docSource": "MIDNIGHTTRADER",
        "source": "MTClosing",
        "dateTime": "2015-10-23T16:42:46-05:00",
        "link": "Markets/News",
        "docKey": "1413-A1067083-1B14K77PVTUM1O7PCAFMI3SJO4",
    },

3 个答案:

答案 0 :(得分:1)

data的值是一个包含一个对象的JSON数组,而不是一个对象本身。

要在data中获取该对象,请使用以下内容替换引发异常的行:

JSONObject json2 = json.getJSONArray("data").get(0);

这会将data数组作为JSONArray对象,然后获取第0个元素,这是您想要的对象。

答案 1 :(得分:0)

您的数据"对象",实际上不是一个对象,它是一个数组,请注意开放的方括号...我在您的实际代码中假设,它也会关闭。

"data": [{
  "headline": "Close Update"
  "docSource": "MIDNIGHTTRADER",
  "source": "MTClosing",
  "dateTime": "2015-10-23T16:42:46-05:00",
  "link": "Markets/News",
  "docKey": "1413-A1067083-1B14K77PVTUM1O7PCAFMI3SJO4",
}]

尝试json.getJSONArray(" data")[0]代替......或者你需要的任何索引

try {
        JSONObject json = (JSONObject) new JSONTokener(result).nextValue();
        System.out.println(json);
        JSONObject json2 = json.getJSONArray("data")[0];
        String test = json2.getString("headline");
        System.out.println(test);
    }
catch (JSONException e) {
        e.printStackTrace();

答案 2 :(得分:0)

你的问题是基于你的服务返回和数组而不是单个json对象的事实,所以从这里你可以按照这个建议直接从JSONArray Can't access getJSONArray in java处理,或者在服务器端你可以将响应数组封装到另一个对象中(java示例):

public class Data<T> {

    private List<T> elements;

    public ObjectSugetionsDTO(){

并按照以下方式构建响应:

return new ResponseEntity<Data<YourInternalRepresentation>>(
                    new Data<YourInternalRepresentation>(yourMethodCallForTheArray()),
                    HttpStatus.OK);

我找到了第二种方法,可以更好地保持我的API清洁和可读性

编辑:更好的方式

我还建议使用改造(http://square.github.io/retrofit/),通过这样做,您的服务调用将恢复为(调用示例和检索用户列表的API):

public class UserService {

    public static IUserService getUserService() {
        return RestAdapterManager.createService(IUserService.class );
    }

    public interface IUserService{
        @GET("/api/users")
        public void getAllUsers(Callback<List<User>> callback);

    }
}

和服务调用本身

UserService.getUserService().getAllUsers(new Callback<List<User>>() {
                    @Override
                    public void success(List<User> users, Response response) {
                        Log.d("Exito! " , "" + users.size());
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        Log.d("Fail!", error.getUrl());
                    }
                });

连接对象的简单本体化

public static <S> S createService(Class<S> serviceClass, String username, String password) {
    RestAdapter.Builder builder = new RestAdapter.Builder()
        .setEndpoint(API_BASE_URL);//Your api base url

    RestAdapter adapter = builder.setLogLevel(RestAdapter.LogLevel.FULL).build(); //change the logging level if you need to, full is TOO verbose
    return adapter.create(serviceClass);
}
相关问题