2013-02-07 11 views
6

Mam JSON (pokazany poniżej), staram się analizować przez cały JSON, a każdy obiekt będzie nowa instancja klasy, która deklaruje zmienne poniżej. Jaki jest najlepszy sposób na zrobienie tego? Należy użyć JSONReader lub użyć JSONObject i JSONArray. Czytałem kilka tutoriali i zadawałem ogólne pytania, ale nie widziałem żadnych przykładów, jak analizować dane takie jak to.Analizować dane JSON wykorzystujące JSONReader lub JSONObject/JSONArray

{ 
    "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 
         } 
        ] 
       } 
      ] 
     } 
    ] 
} 

Odpowiedz

2

gdybym miał to zrobić, będę analizować cały ciąg do JSONObject

JSONObject obj = new JSONObject(str); 

następnie widzę, że twoje podkategorie to JSONArray. Więc będzie przekształcić go jak ten

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

z tym można zrobić pętlę i instancję Twój obiekt klasy

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

GSON to najprostszy sposób, gdy trzeba pracować z zagnieżdżonymi obiektami.

tak:

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

Można sprawdzić samouczek, http://androidsmith.com/2011/07/using-gson-to-parse-json-on-android/ lub http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html lub http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

0

Przykład JSON dane zamieszczone nie wydaje się podążać strukturę danych JSON jest. Będziesz musiał zbudować dane dokładnie w taki sam sposób, jak uczy się w trzecim link opublikowanym przez Mustafę. To naprawdę świetny samouczek. Postępowałem zgodnie z instrukcjami i to naprawdę działa!

8

Możesz używać obiektu JSON Object/JSON Array tylko, jeśli rozmiar danych json jest mniejszy niż 1 MB. Inaczej powinieneś pójść z JSONReaderem. JSONReader faktycznie korzysta strumieniowego podejście podczas JSONObject i JSONArray ostatecznie załadować wszystkie dane na temat pamięci RAM na raz, co powoduje OutOfMemoryException w przypadku większego JSON.

+5

'Można wykorzystać JSON Object/JSON Array tylko jeśli rozmiar danych json jest mniejszy niż 1 MB "Gdzie te informacje są oficjalnie udokumentowane? – AADProgramming

1

jest to prosty przykład użycia Gson do modelowania ArrayList obiektów poprzez JsonReader:

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

a obiekt i modelowanego:

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"; 
} 
Powiązane problemy