【问题标题】:failed to process json data in android无法在android中处理json数据
【发布时间】:2015-04-22 17:56:10
【问题描述】:
[{"acteurid":"86744570","productions":[{"variete":"Riz","recolte":"10000"}],"nom":"Charles Diouf"},{"acteurid":"6535150","productions":[{"variete":"Riz","recolte":"1000"}],"nom":"Daba Diouf"},{"acteurid":"86817462","productions":[{"variete":"Riz","recolte":"8000"}],"nom":"Diel Ndour"},{"acteurid":"14047190","productions":[{"variete":"Ble","recolte":"10000"},{"variete":"Mais","recolte":"1000"},{"variete":"Mais","recolte":"2000"},{"variete":"Riz","recolte":"5000"},{"variete":"Ble","recolte":"8000"}],"nom":"Hamady Diouf"}]

我如何读取上面的 json 数据?我想在ListView 中显示如下:

  1. 名义
  2. 多样化
  3. 回忆
  4. .variete
  5. .recolte
  6. 。 . . .
  7. 名义
  8. 多样化
  9. 回忆

我尝试了以下代码,但列表未显示。我有

FATAL EXCEPTION: main
java.lang.NullPointerException at 
       pcom.jsontest.MyCustomAdapter.getView(MyCustomAdapter.java:32)

代码是

for(int i=0;i<jarray.length();i++){
            JSONObject json=jarray.getJSONObject(i);

            JSONArray prodar=json.getJSONArray("productions");
            for(int j=0;j<prodar.length();j++){
                JSONObject prod=prodar.getJSONObject(j);
                Production production = new Production(prod.getString("variete"),prod.getString("recolte"));
                productions.add(production);
            }

            Producteur producteur=new Producteur(json.getString("acteurid"),productions,json.getString("nom"));
            producteurs.add(producteur);
        }


MyCustomAdapter adapter = new MyCustomAdapter(this,producteurs);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);

自定义数组适配器

public class MyCustomAdapter extends ArrayAdapter<Producteur> {
    public MyCustomAdapter(Context context, ArrayList<Producteur> prods) {
        super(context, 0, prods);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        Producteur producteur = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
        }
        // Lookup view for data population
        TextView name = (TextView) convertView.findViewById(R.id.name);
        name.setText(producteur.getNom());

        ArrayList<Production> productions=producteur.getProductions();
        ListView listprod = (ListView) convertView.findViewById(R.id.list);
        ArrayAdapter<Production> productionsAdapter = new ArrayAdapter<Production>(getContext(), R.layout.list_prod_item, productions);
        listprod.setAdapter(productionsAdapter);

       // Return the completed view to render on screen
        return convertView;
    }
}

list_item.xml

 <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/nom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" />
    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    </LinearLayout>

list_prod_item.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/variete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/recolte"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" />

</LinearLayout>

【问题讨论】:

  • 我不确定你的意思。第一项是String,第二项是String to。
  • 这就是您需要解析的所有数据吗?因为那是一个只有一项的 ArrayList ([{},{},..])。因此,当您执行jarray.getJSONObject(i) 时,您将获得全部数据。我明白这不是你想要的?你想做什么?
  • @BishopBarber 我想显示我发布的 json 数据中的值。我通过在 servlet 中使用 json.put(id, member) 在应用程序服务器中创建它。第二个值包含子值。
  • 等等,所以你不想读取json数据,而是将json数据发送到你的servlet?
  • @BishopBarber 抱歉,我已经编辑了我的帖子。我想读取json数据。

标签: java android json android-listview


【解决方案1】:

为了完成 dilix 的示例,假设您的模型名为 Producteur

public class Producteur {
    // Private attributes
    private int mId;
    // List of Produit, which is another model or object (call it however you want) created by you.
    private List<Produit> mProduits;
    private String mNom;

    // Attributes getters and setters (they are optionnal in this example, but it's always good idea to have them)
    public int get_mId() { return this.mId; }
    public void set_mId(int id) { this.mId = id; }

    public List<Produit> get_mProduits() { return this.mProduits; }
    public void set_mProduits(List<Produit> produits) { this.mProduits = produits; }

    public String get_mNom() { return this.mNom; }
    public void set_mNom(String nom) { this.mNom= nom; }

    // Constructor
    public Producteur(int id, List<Produit> produits, String nom) {
        this.mId = id;
        this.mProduits = produits;
        this.mNom = nom;
    }
}

然后您的模型Produit 将代表生产者的产品之一:

public class Produit {
    // A product has two attributes: variete and recolte. I'll let you complete 
    // this class, you can inspire yourself of the above example.
}

现在是时候在数据读取中使用这两个对象了:

// Instead of a hashmap, we'll be using a list of "Producteur"
List<Producteur> producteurs = new List<Producteur>();
JSONArray jarray=new JSONArray(resSel);
//String acteur_id="";
for(int i=0;i<jarray.length();i++){
    JSONObject json = jarray.getJSONObject(i);

    int id = json.getInt("acteurid");
    // Note the name is not part of the "productions" JSONArray
    String nom = json.getString("nom");

    // Here we'll declare the productor's productions
    List<Produit> productions = new List<Produit>();

    JSONArray prodar=json.getJSONArray("productions");
    for(int j=0;j<prodar.length();j++){
        JSONObject prod=prodar.getJSONObject(j);
        String variete = prod.getString("variete");
        int recolte = Integer.parseInt(prod.getString("recolte"));

        // We'll create a new "Produit" at each loop and add it to the productor's product list.
        Produit unProduit = new Produit(variete, recolte);
        productions.add(unProduit);
    }

    // We'll create a new productor at each loop and add it to the productors list
    Producteur unProducteur = new Producteur(id, productions, nom); 
    producteurs.add(unProducteur);
}

然后,要将其添加到 listView 中,您可以使用 ArrayAdapter&lt;Producteur&gt;

ListView listprod = (ListView)findViewById(R.id.list);
// We will passe the list of "Producteur" we just created above as the objects to represent in the ListView
ArrayAdapter<Producteur> producteursAdapter = new ArrayAdapter<Producteur>(this, R.layout.list_item, producteurs);
listprod.setAdapter(producteursAdapter);

请注意,这是在 ListView 中显示您的产品的最基本方式。如果要自定义对象显示,请检查 this link

【讨论】:

  • 列表无法显示。我的 list_item.xml 是否正确?
  • 致命异常:main java.lang.IllegalStateException:ArrayAdapter 要求资源 ID 为 TextView
  • @PaulNgom 您的布局看起来不错。您是否实现了一个自定义的 ArrayAdapter,如 here 所示?如果是这样,您可以发布代码吗?
  • @PaulNgom 你进步了,干得好!虽然,我在您的代码中发现了两个问题。首先,在您的自定义 ArrayAdapter 中,您有这一行:TextView name = (TextView) convertView.findViewById(R.id.name);。请注意,在您的 list_item.xml 布局中,您的 TextView 的 id 是 nom 而不是 name
  • @PaulNgom 第二个错误是填充产品 ListView。此行:ArrayAdapter&lt;Production&gt; productionsAdapter = new ArrayAdapter&lt;Production&gt;(getContext(), R.layout.list_prod_item, productions); 不起作用。如果您检查您正在使用的 ArrayAdapter 构造函数,您可以看到第二个参数 resource 期待 The resource ID for a layout file containing a TextView to use when instantiating views...
【解决方案2】:

如果您通过http://json.parser.online.fr/ 可视化您的 json 您将看到整个 JSON 的层次结构。

从这一点来说,我建议你让你建模为:

public class Model {
    int mId;
    List<Product> mProducts;
    String mName;
}

您应该能够根据此模型解析您的 json,然后使用它来可视化列表中的项目或您想要的任何位置。

例如当你有

List<Model>;

你可以使用

ArrayAdapter<Model>;

【讨论】:

  • 您可以使用 gson 例如 javacodegeeks.com/2011/01/… 或者您仍然可以使用 JSON 对象和 JSONarray 自己解析它。当你解析它时,像 java/android 中的其他模型一样使用它。
猜你喜欢
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多