简体   繁体   English

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

[英]How do I get data from JSON string?

Here is my code: 这是我的代码:

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

My String values start with the object data . 我的String值以对象数据开头。 So I am trying to get that object first and then capture the the object headline inside that. 因此,我尝试首先获取该对象,然后捕获其中的对象标题

My problem is, it is not taking the object data from the string. 我的问题是,它不是从字符串中获取对象数据 Once I reach the line JSONObject json2 = json.getJSONObject("data"); 一旦到达行JSONObject json2 = json.getJSONObject("data"); , it throws the exception. ,它将引发异常。 Please shed some light on this. 请对此有所说明。

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

The value for the key data is a JSON array containing one object, and not an object itself. 密钥data的值是一个JSON数组,其中包含一个对象,而不是对象本身。

To get that object inside data , replace your line that throws an exception with the following: 为了使该对象包含在data ,请将引发异常的行替换为以下内容:

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

This gets the data array as a JSONArray object and then gets the 0th element, which is the object you want. 这将data数组作为JSONArray对象获取,然后获取第0个元素,即您想要的对象。

Your data "object", isn't actually an object, it's an array, notice the opening square bracket... I'm assuming in your actual code, it closes with one too. 您的数据“对象”实际上不是一个对象,它是一个数组,请注意方括号...我在您的实际代码中假设,它也以一个结束。

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

Try json.getJSONArray("data")[0] instead... or whatever index you need 尝试改用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();

Your problem is based on the fact that your service returns and array instead of a single json object, so from here you can follow this suggestions to process directly from the JSONArray Can't access getJSONArray in java , or, at server side you can encapsulate your response array into another object like this (java example): 您的问题基于服务返回和数组而不是单个json对象这一事实,因此从这里您可以按照以下建议从JSONArray直接处理无法访问java中的getJSONArray ,或者在服务器端可以封装您的响应数组到另一个这样的对象中(java示例):

public class Data<T> {

    private List<T> elements;

    public ObjectSugetionsDTO(){

And build the response like this: 并构建如下响应:

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

I have found the second way to be better at keeping my API cleaner and more readable 我发现第二种方法可以更好地保持API的清洁度和可读性

EDIT: Better way 编辑:更好的方法

I whould also suggest the use of retrofit ( http://square.github.io/retrofit/ ), by doing so, your service calls is resumed to (Example of calling and API that retrieves a list of users): 我还建议使用改造( 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);

    }
}

and the service call itself 和服务本身

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

The simple inicialization of the connection object 连接对象的简单初始化

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM