簡體   English   中英

如何從JSON字符串獲取數據?

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

這是我的代碼:

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

我的String值以對象數據開頭。 因此,我嘗試首先獲取該對象,然后捕獲其中的對象標題

我的問題是,它不是從字符串中獲取對象數據 一旦到達行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",
    },

密鑰data的值是一個JSON數組,其中包含一個對象,而不是對象本身。

為了使該對象包含在data ,請將引發異常的行替換為以下內容:

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

這將data數組作為JSONArray對象獲取,然后獲取第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();

您的問題基於服務返回和數組而不是單個json對象這一事實,因此從這里您可以按照以下建議從JSONArray直接處理無法訪問java中的getJSONArray ,或者在服務器端可以封裝您的響應數組到另一個這樣的對象中(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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM