簡體   English   中英

如何將 JSONArray 轉換為 ArrayList?

[英]How to convert JSONArray to ArrayList?

我花了兩天時間思考這個問題,但未能解決。 所以請幫忙。

這是我的 json 模型

{
  "order_room_number": "string",
  "order_breakfast": "string",
  "room_type_name": "string",
  "order_number": "string",
  "hotel_id": 0,
  "order_check_in_time": "2017-03-09T10:56:09.343Z",
  "order_price": "string",
  "hotel_addres": "string",
  "order_check_out_time": "2017-03-09T10:56:09.343Z",
  "hotel_name": "string",
  "order_phone": "string",
  "order_transactionid": "string",
  "order_date": "2017-03-09T10:56:09.343Z",
  "user_id": 0,
  "order_people_number": 0,
  "order_id": 0,
  "order_state": "string",
  "order_number_of_room": 0,
  "orderUserList": [
    {
      "order_user_id": 0,
      "order_user_name": "string",
      "order_user_phone": "string",
      "order_id": 0,
      "order_user_id_number": "string"
    }
  ]
}

這是我的 json,我需要將其轉換為 ArrayList

{
  "status": 200,
  "msg": "OK",
  "data": [
    {
      "order_id": 12,
      "order_number": null,
      "order_transactionid": "9",
      "order_date": null,
      "order_check_in_time": 1488680530000,
      "order_check_out_time": 1488680530000,
      "order_breakfast": null,
      "order_number_of_room": null,
      "order_room_number": null,
      "order_people_number": null,
      "order_phone": null,
      "order_price": "9",
      "order_state": "1",
      "room_type_name": null,
      "hotel_name": null,
      "hotel_addres": null,
      "hotel_id": null,
      "user_id": null,
      "orderUserList": null
    }
  ]
}

這是我的模型

package com.example.wecheatpaydemo.Model;

/**
 * 
 *
 * @Explain:
 */

public class OrderUser {


    private Long order_user_id;             // 用戶實名制里面的姓名
    private String order_user_name;         // 用戶實名制里面的姓名
    private String order_user_phone;        // 用戶的手機號,用作登錄賬號
    private String order_user_id_number;    // 用戶身份證號碼
    private String order_id;                // 訂單表外鍵

    public Long getOrder_user_id() {
        return order_user_id;
    }

    public void setOrder_user_id(Long order_user_id) {
        this.order_user_id = order_user_id;
    }

    public String getOrder_user_name() {
        return order_user_name;
    }

    public void setOrder_user_name(String order_user_name) {
        this.order_user_name = order_user_name;
    }

    public String getOrder_user_phone() {
        return order_user_phone;
    }

    public void setOrder_user_phone(String order_user_phone) {
        this.order_user_phone = order_user_phone;
    }

    public String getOrder_user_id_number() {
        return order_user_id_number;
    }

    public void setOrder_user_id_number(String order_user_id_number) {
        this.order_user_id_number = order_user_id_number;
    }

    public String getOrder_id() {
        return order_id;
    }

    public void setOrder_id(String order_id) {
        this.order_id = order_id;
    }

    @Override
    public String toString() {
        return "OrderUser{" +
                "order_user_id=" + order_user_id +
                ", order_user_name='" + order_user_name + '\'' +
                ", order_user_phone='" + order_user_phone + '\'' +
                ", order_user_id_number='" + order_user_id_number + '\'' +
                ", order_id='" + order_id + '\'' +
                '}';
    }

    public OrderUser(Long order_user_id, String order_user_name, String order_user_phone, String order_user_id_number, String order_id) {
        this.order_user_id = order_user_id;
        this.order_user_name = order_user_name;
        this.order_user_phone = order_user_phone;
        this.order_user_id_number = order_user_id_number;
        this.order_id = order_id;
    }

    public OrderUser() {
    }

}

這是我的片段

public class ListChoiceone extends Fragment {
    private RecyclerView recyclerView;
    private List<Order> listBean;
    private RecyclerAdapter adapter;
    private String url = "http://jm/user/order/getNPayedOrders?user_id=9";


    public ListChoiceone() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_list_choiceone, container, false);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
        initData();
        adapter = new RecyclerAdapter(listBean, getActivity());
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        sendRequestWithHttpClicent();

        return view;


    }

    private void sendRequestWithHttpClicent() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSONWithJSONObject(responseData);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void parseJSONWithJSONObject(String jsonData) {
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            String status = jsonObject.getString("status");
            String msg = jsonObject.getString("msg");

            JSONArray jsonArray = jsonObject.getJSONArray("data");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                int order_id = json.getInt("order_id");

                String order_number = json.getString("order_number");
                String order_transactionid = json.getString("order_transactionid");
                String order_phone = json.getString("order_phone");
                String order_state = json.getString("order_state");
                String order_check_in_time = json.getString("order_check_in_time");
                String order_check_out_time = json.getString("order_check_out_time");
                String order_price = json.getString("order_price");
                String hotel_name = json.getString("hotel_name");
                String hotel_addres = json.getString("hotel_addres");
                String order_room_number = json.getString("order_room_number");
                String room_type_name = json.getString("room_type_name");

                int hotel_id = json.getInt("hotel_id");
                int user_id = json.getInt("user_id");

                JSONArray jsonArrayOrder = json.getJSONArray("orderUserList");
                ArrayList<OrderUser> listOrderUser = new ArrayList<OrderUser>();


                Log.i("nige", order_state);

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initData() {
        listBean = new ArrayList<>();



    }

}

非常感謝我的編碼朋友們!

簡單的例子:

List<Model> data = new ArrayList<>();

JSONArray jsonArray = jsonObject.getJSONArray("data");

for (int i = 0; i < jsonArray.length(); i++) {
   data.add(new Model(/*fill your data*/));  
}

在 for 循環之前移動它

  ArrayList<OrderUser> listOrderUser = new ArrayList<OrderUser>();

然后簡單地添加一個項目, listOrderUser.add(<your_model_item>);

在 for 循環之后,做一個 notifyDataSetChanged(); 在 recyclerView 適配器上

將此庫添加到 gradle:

implementation 'com.google.code.gson:gson:2.8.5'

進而:

 ArrayList<model> data = new Gson().fromJson(myJSONArray.toString(),
 new TypeToken<List<model>>(){}.getType());

使用 GSON 和 Kotlin,你只需要這個:

        val arr = Gson().fromJson(jsonArrayInString, Array<T>::class.java)
    {"myjson":[{"name":"Rajkumar","place":"Erode","gender":"male"},{"name":"Dineshkumar","place":"Erode","gender":"male"},
    {"name":"Saravanakumar","place":"mettur","gender":"male"}
    {"name":"Jayakumar","place":"chennai","gender":"male"}]}

    List<RajObj> list = new ArrayList<>();
    if (op!= null) { 
      int len = myjson.length();
      for (int i=0; i< len; i++) { 
        JSONObject o = (JSONObject) op.get(i);
        list.add(new RajObj(o.getString('name'), o.getString('place'), o.getString('gender')));
      } 
    } 
    System.out.println("Result " + list.size() + " objects.");
    public static final class RajObj {
      final String name;
      final String place;
      final String gender;
      public RajObj(String name, String place, String gender) {
         this.name = name;
         this.place  = place;
         this.gender = gender;
      }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM