2013-02-07 36 views
6

我有一些JSON(如下所示),我試圖解析整個JSON,每個對象將是一個聲明下面變量的類的新實例。做這個的最好方式是什麼?我應該使用JSONReader還是使用JSONObject和JSONArray。我一直在閱讀一些教程,並提出一些一般問題,但我沒有看到任何如何解析這樣的數據的例子。使用JSONReader或JSONObject/JSONArray解析JSON數據

{ 
    "id": 356, 
    "hassubcategories": true, 
    "subcategories": [ 
     { 
      "id": 3808, 
      "CategoryName": "Current Products", 
      "CategoryImage": null, 
      "hassubcategories": true, 
      "subcategories": [ 
       { 
        "id": 4106, 
        "CategoryName": "Architectural", 
        "CategoryImage": "2637", 
        "hassubcategories": true, 
        "subcategories": [ 
         { 
          "id": 391, 
          "CategoryName": "Flooring", 
          "CategoryImage": "2745", 
          "hassubcategories": false 
         } 
        ] 
       } 
      ] 
     }, 
     { 
      "id": 3809, 
      "CategoryName": "Non-Current Products", 
      "CategoryImage": null, 
      "hassubcategories": true, 
      "subcategories": [ 
       { 
        "id": 4107, 
        "CategoryName": "Desk", 
        "CategoryImage": "2638", 
        "hassubcategories": true, 
        "subcategories": [ 
         { 
          "id": 392, 
          "CategoryName": "Wood", 
          "CategoryImage": "2746", 
          "hassubcategories": false 
         } 
        ] 
       } 
      ] 
     } 
    ] 
} 

回答

2

,如果我是這樣做,我將整個字符串解析到一個JSONObject

JSONObject obj = new JSONObject(str); 

然後我看到你的子類是一個JSONArray。所以我將其轉換這樣

JSONArray arr = new JSONArray(obj.get("subcategories")); 

有了這個,你可以做一個循環和實例化類對象

for(int i = 0; i < arr.length; i++) 
JSONObject temp = arr.getJSONObject(i); 
Category c = new Category(); 
c.setId(temp.get("id")); 
4

當你必須使用嵌套對象時,GSON是最簡單的方法。

這樣的:

//after the fetched Json: 
Gson gson = new Gson(); 

Event[] events = gson.fromJson(yourJson, Event[].class); 

//somewhere nested in the class: 
static class Event{ 
    int id; 
    String categoryName; 
    String categoryImage; 
    boolean hassubcategories; 
    ArrayList<Event> subcategories; 
} 

您可以檢查此教程,http://androidsmith.com/2011/07/using-gson-to-parse-json-on-android/http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.htmlhttp://www.androidhive.info/2012/01/android-json-parsing-tutorial/

0

比如你發佈似乎並不遵循JSON的數據結構JSON數據。您將需要以與穆斯塔法發佈的第三個link中教導的方式完全相同的方式構建您的數據。這是一個非常棒的教程。我遵循了這些步驟,它確實有效!

8

只有當json數據的大小小於1MB時,纔可以使用JSON對象/ JSON數組。否則,你應該去與JSONReader。 JSONReader實際上使用流式方法,而JSONObject和JSONArray最終一次加載RAM上的所有數據,這會在更大的json情況下導致OutOfMemoryException。

+5

'可以使用JSON對象/ JSON陣列僅當你的json數據的大小小於1MB'這個信息被正式記錄在哪裏? – AADProgramming

1

這是使用GSON用於經由JsonReader對象的建模ArrayList的一個簡單的例子:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    tv = (TextView) findViewById(R.id.textviewtest); 
    Task task = new Task(); 
    task.execute(); 
} 

private class Task extends AsyncTask<Void, Void, ArrayList<Flower>> { 

    @Override 
    protected ArrayList<Flower> doInBackground(Void... params) { 

     ArrayList<Flower> arrayFlowers = new ArrayList<Flower>(); 
     Flower[] f = null; 
     try { 
      String uri = "http://services.hanselandpetal.com/feeds/flowers.json"; 
      URL url = new URL(uri); 
      HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
      Gson gson = new Gson(); 

      JsonReader reader = new JsonReader(new InputStreamReader(con.getInputStream())); 
      f = gson.fromJson(reader, Flower[].class); 

      for (Flower flower : f) { 
       arrayFlowers.add(flower); 
      } 
     } catch (MalformedURLException e) { 
      return null; 
     } catch (IOException e) { 
      return null; 
     } 
     return arrayFlowers; 
    } 
    @Override 
    protected void onPostExecute(ArrayList<Flower> result) { 
     StringBuilder sb = new StringBuilder(); 
     for (Flower flower : result) { 
      sb.append(flower.toString()); 
     } 
     tv.setText(sb.toString()); 
    } 
} 

和我建模的對象:

public class Flower { 

private String category; 
private double price; 
private String instructions; 
private String photo; 
private String name; 
private int productId; 

public String getCategory() { 
    return category; 
} 
public void setCategory(String category) { 
    this.category = category; 
} 
public double getPrice() { 
    return price; 
} 
public void setPrice(double price) { 
    this.price = price; 
} 
public String getInstructions() { 
    return instructions; 
} 
public void setInstructions(String instructions) { 
    this.instructions = instructions; 
} 
public String getPhoto() { 
    return photo; 
} 
public void setPhoto(String photo) { 
    this.photo = photo; 
} 
public String getName() { 
    return name; 
} 
public void setName(String name) { 
    this.name = name; 
} 
public int getProductId() { 
    return productId; 
} 
public void setProductId(int productId) { 
    this.productId = productId; 
} 
@Override 
public String toString() { 
    return getProductId() + " : " + name + "\n" + price + "$" + "\n" + "\n"; 
}