如何使用gson迭代json数据

时间:2017-08-01 23:03:32

标签: java json gson

我的json字符串是:

{
   "recordsTotal":1331,
   "data":[
      {
         "part_number":"3DFN64G08VS8695 MS",
         "part_type":"NAND Flash",
         "id":1154,
         "manufacturers":[
            "3D-Plus"
         ]
      },
      {
         "part_number":"3DPM0168-2",
         "part_type":"System in a Package (SiP)",
         "id":452,
         "manufacturers":[
            "3D-Plus"
         ]
      },
      {
         "part_number":"3DSD1G16VS2620 SS",
         "part_type":"SDRAM",
         "id":269,
         "manufacturers":[
            "3D-Plus"
         ]
      }
   ]
}

此代码允许我访问两个最高级别的元素:

JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject(); 
System.out.println("data : " + jsonObject.get("data")); 
System.out.println("recordsTotal : " + jsonObject.get("recordsTotal"));

但我想做的是遍历“data”中的所有对象并创建part_numbers列表。我该怎么做?

3 个答案:

答案 0 :(得分:1)

JsonArray is an Iterable<JsonElement>。所以你可以用于循环。

JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
final JsonArray data = jsonObject.getAsJsonArray("data");
System.out.println("data : " + data);
System.out.println("recordsTotal : " + jsonObject.get("recordsTotal"));
List<String> list = new ArrayList<String>();
for (JsonElement element : data) {
    list.add(((JsonObject) element).get("part_number").getAsString());

}

答案 1 :(得分:0)

给定的代码不能保证100%等效,但它可以帮助您工作。

首先,您必须为数据对象创建类:

class mydata {
    public String part_name;
    public String part_type;
    public int Id;
    public String manufacturers;
}

您的主要方法应该是

public static void main(String[] args) {

JSONObject obj = new JSONObject();
List<mydata> sList = new ArrayList<mydata>();

mydata obj1 = new mydata();
obj1.setValue("val1");
sList.add(obj1);

mydata obj2 = new mydata();
obj2.setValue("val2");
sList.add(obj2);

obj.put("list", sList);

JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
  System.out.println(jArray.getJSONObject(ii).getString("value"));
    }

如需进一步探索,您可以使用该链接: https://gist.github.com/codebutler/2339666

答案 2 :(得分:0)

假设Json Model的类名是Example。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/colorPrimaryDark"
    >
    <com.abc.customslider.CustomSeekbar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:layout_margin="20dp"
        android:thumb="@drawable/thumb"
        android:thumbOffset="1dp"
        android:progressDrawable="@drawable/progress_drawable"
        />

</LinearLayout>

假设数据类名列表是基准: -

@Override
protected synchronized void onDraw(final Canvas canvas) {
    super.onDraw(canvas);


    final int width = getMeasuredWidth();
    final int step = width / getMax();

    if(mDotBitmap!=null)
    Log.d("cs",""+mDotsPositions.length+":"+step+":"+getProgress());

    if (null != mDotsPositions && 0 != mDotsPositions.length && null != mDotBitmap) {

        for (int position : mDotsPositions) {

            Paint paint = new Paint();

            Log.d("cs",""+position);

            int progress = getProgress();


            if(position<50)
            {
                if(progress > position)
                {
                    paint.setColorFilter(new PorterDuffColorFilter(getResources().getColor(R.color.colorStart), PorterDuff.Mode.SRC_IN));



                }
                else{
                    paint.setColorFilter(new PorterDuffColorFilter(getResources().getColor(android.R.color.darker_gray), PorterDuff.Mode.SRC_IN));

                }
            }
            else{
                if(progress >= position)
                {
                    paint.setColorFilter(new PorterDuffColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_IN));
                }
                else{
                    paint.setColorFilter(new PorterDuffColorFilter(getResources().getColor(android.R.color.darker_gray), PorterDuff.Mode.SRC_IN));


                }
            }

            canvas.drawBitmap(mDotBitmap, position*step ,0, paint);

        }
    }
}

然后通过Gson库我们可以将json转换为java Model:

import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Example {

    @SerializedName("recordsTotal")
    private Integer recordsTotal;
    @SerializedName("data")
    private List<Datum> data = null;

    public Integer getRecordsTotal() {
        return recordsTotal;
    }

    public void setRecordsTotal(Integer recordsTotal) {
        this.recordsTotal = recordsTotal;
    }

    public List<Datum> getData() {
        return data;
    }

    public void setData(List<Datum> data) {
        this.data = data;
    }

}

现在我们可以通过示例模型获取数据列表: -

import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Datum {

    @SerializedName("part_number")

    private String partNumber;
    @SerializedName("part_type")

    private String partType;
    @SerializedName("id")

    private Integer id;
    @SerializedName("manufacturers")

    private List<String> manufacturers = null;

    public String getPartNumber() {
        return partNumber;
    }

    public void setPartNumber(String partNumber) {
        this.partNumber = partNumber;
    }

    public String getPartType() {
        return partType;
    }

    public void setPartType(String partType) {
        this.partType = partType;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public List<String> getManufacturers() {
        return manufacturers;
    }

    public void setManufacturers(List<String> manufacturers) {
        this.manufacturers = manufacturers;
    }

}

从dataList,您可以遍历并获取所有信息。

如果我们需要partNmber List,那么我们可以这样: -

Example example = new Gson().fromJson(jsonString, new TypeToken<Example>() {}.getType());