如何将对象列表转换为jsonObject?

时间:2017-07-21 06:25:02

标签: android json list gson

如何将对象列表转换为jsonObject?

  

我正在将Pojo类的列表转换为jsonObject。我将整个列表转换为jsonArray,但是如何从数组范围中添加其他字段?

            List<Order> items = new ArrayList<>();
            if (checkOutList != null) {
                for (Category.Items i1 : checkOutList) {
                    Order order = new Order();
                    order.setC_id(i1.getCid());
                    order.setItem_id(i1.getItem_id());
                    order.setQuantity(i1.getCount());
                    items.add(order);
                }
                Order order = new Order();
                order.setOd_total_cost(cardValue.getText().toString().trim());
                order.setR_id(checkOutList.get(0).getRid());
                order.setU_id("5");
                items.add(order);

                Gson gson = new GsonBuilder().create();
                JsonArray myCustomArray = gson.toJsonTree(items).getAsJsonArray();
                Log.e("order", myCustomArray.toString());
            }

上面的代码给了我输出:

[{"c_id":"3","item_id":"18","quantity":"5"},{"od_total_cost":"Card Value: $30.14","r_id":"1","u_id":"5"}]

输出我想要

{"items":[{"quantity":"25","c_id":"70","item_id":"10"}],"r_id":"5","u_id":"70","od_total_cost":"20000"}

更新

JsonElement jsonObject=gson.toJsonTree(order);
Log.e("order", myCustomArray.toString()+jsonObject.toString());
  

上面添加的一行给了我以下现在如何添加arrayname:items?并将整个输出添加为json对象

[{"c_id":"3","item_id":"18","quantity":"5"},{"c_id":"3","item_id":"17","quantity":"2"},{"c_id":"2","item_id":"91","quantity":"2"},{"c_id":"2","item_id":"9","quantity":"1"}]{"od_total_cost":"Card Value: $20.16","r_id":"1","u_id":"5"}

4 个答案:

答案 0 :(得分:1)

我认为其他方式也有效,但我也可以使用POJO。

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/slide_side_menu"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:fitsSystemWindows="true"
android:background="#fff"
tools:context="app.mes..MainActivity"
android:gravity="center">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimaryDark"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>


<com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/appbar"
    android:layout_centerHorizontal="true"
    ads:adSize="SMART_BANNER"
    ads:adUnitId="@string/banner_id">
</com.google.android.gms.ads.AdView>

    <FrameLayout
        android:id="@+id/drawer_container"
        android:layout_below="@id/adView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

            <FrameLayout
                android:id="@+id/frame_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">

                        <com.app.mes..views.CustomSwipeRefresh
                            android:id="@+id/swipe_refresh"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layout_alignParentTop="true"
                            android:layout_alignParentStart="true">

                            <ViewStub
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:id="@+id/view_stub"
                                android:layout_alignParentTop="true"
                                android:layout_alignParentStart="true" />
                        </com.app.mes.views.NCCustomSwipeRefresh>
                    </RelativeLayout>
            </FrameLayout>

    </FrameLayout>

    <devlight.io.library.ntb.NavigationTabBar
        android:id="@+id/ntb_horizontal"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        app:ntb_badge_gravity="top"
        android:layout_alignParentBottom="true"
        app:ntb_bg_color="@color/colorPrimaryDark"
        app:ntb_inactive_color="@android:color/white"
        app:ntb_badge_position="right"
        app:ntb_badged="true"
        app:ntb_scaled="true"
        app:ntb_tinted="true"
        app:ntb_title_mode="all"
        app:ntb_titled="true"
        app:ntb_swiped="true"/>

答案 1 :(得分:0)

制作一个Json对象并添加如下的值

 List<Order> items = new ArrayList<>();
        if (checkOutList != null) {
            for (Category.Items i1 : checkOutList) {
                Order order = new Order();
                order.setC_id(i1.getCid());
                order.setItem_id(i1.getItem_id());
                order.setQuantity(i1.getCount());
                items.add(order);
            }


            Gson gson = new GsonBuilder().create();
            JsonArray myCustomArray = gson.toJsonTree(items).getAsJsonArray();
            Log.e("order", myCustomArray.toString());




     JsonObject ob= new JsonObject();
        ob.put("items",myCustomArray);
        ob.put("od_total_cost",cardValue.getText().toString().trim());
         ob.put("r_id",checkOutList.get(0).getRid());
         ob.put("u_id","5");


       Log.e("order", ob.toString());

答案 2 :(得分:0)

使用:

new Gson().toJson(yourObject)

答案 3 :(得分:0)

请按照以下步骤操作。

第1步: 添加下面的依赖项并同步您的gradle。

compile 'com.google.code.gson:gson:2.6.2'

第2步:

在模型包中添加以下两个类。

<强> MyItem.java

public class MyItem {

    @SerializedName("items")
    private List<Order> mItems;
    @SerializedName("od_total_cost")
    private String mOdTotalCost;
    @SerializedName("r_id")
    private String mRId;
    @SerializedName("u_id")
    private String mUId;

    public List<Order> getItems() {
        return mItems;
    }

    public void setItems(List<Order> items) {
        mItems = items;
    }

    public String getOdTotalCost() {
        return mOdTotalCost;
    }

    public void setOdTotalCost(String odTotalCost) {
        mOdTotalCost = odTotalCost;
    }

    public String getRId() {
        return mRId;
    }

    public void setRId(String rId) {
        mRId = rId;
    }

    public String getUId() {
        return mUId;
    }

    public void setUId(String uId) {
        mUId = uId;
    }
}

<强> Order.java

public class Order {

    @SerializedName("c_id")
    private String mCId;
    @SerializedName("item_id")
    private String mItemId;
    @SerializedName("quantity")
    private String mQuantity;

    public String getCId() {
        return mCId;
    }

    public void setCId(String cId) {
        mCId = cId;
    }

    public String getItemId() {
        return mItemId;
    }

    public void setItemId(String itemId) {
        mItemId = itemId;
    }

    public String getQuantity() {
        return mQuantity;
    }

    public void setQuantity(String quantity) {
        mQuantity = quantity;
    }
}

第3步:

将下面的代码放在要将对象转换为字符串的类中。在这里,我只是在我的主要活动中做到这一点。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Order order = new Order();
    order.setQuantity("25");
    order.setCId("70");
    order.setItemId("10");
    List<Order> orderList = new ArrayList<>();
    orderList.add(order);
    MyItem myItem = new MyItem();
    myItem.setItems(orderList);
    myItem.setRId("5");
    myItem.setUId("70");
    myItem.setOdTotalCost("2000");

    String str=covertObjectToString(myItem);

    Log.e("Tag","Reseponse String "+str);
}

private String covertObjectToString(Object object) {
    return new Gson().toJson(object);
}

完成。

我希望你清楚我的逻辑。