How to get data from this Json?

Asked

Viewed 95 times

0

I need to get the name, Distance, photo and id, which are within "date" and also need to get the route_id that is inside "ride". This will be populated in a listview that contains these first data. By clicking on btn_go, this data will be sent to Activity and also at this time, the route_id must be sent.

Json:

{
  "data": [
    {
      "id": 4,
      "start_address": "Aveninda Treze, Fortaleza - CE",
      "end_address": "Rua Delta, Fortaleza, Ceará 60713, Brazil",
      "start_lat": -3.7464,
      "start_lng": -38.5326,
      "end_lat": -3.79521,
      "end_lng": -38.5772,
      "user_id": 2,
      "distance": "6.521",
      "user": {
        "id": 2,
        "name": "User Test",
        "departure_time": "07:00:00",
        "arrival_time": "18:00:00",
        "address_lat": -3.7952,
        "address_lng": -38.577,
        "car": true,
        "photo_url": "https://test.com/img/avatar_female.png",
        "profile_mode": 2
      },
      "ride": {
        "id": 22,
        "schedule": "2017-03-22 18:00:00",
        "user_id": 2,
        "route_id": 4,
        "chat_id": 57,
        "channel": "chat.57",
        "disabled_reason": 0
      }
    }

Adapter:

 public class SearchAskPresenter extends BaseAdapter implements AdapterView.OnItemClickListener, SubscriptionEventListener {


        private final SearchAskView searchaskview;
        CommunityRequestView viewR;
        private List<UserCommunity> usersList = new ArrayList<UserCommunity>();
        private List<SearchAskConstructor> usersSearchList = new ArrayList<SearchAskConstructor>();
        LayoutInflater inflater;
        TextView txt_Nome;
        TextView txt_Email;
        TextView txt_Distance;
        ImageButton btnGo;
        private UsersMySQLiteHelper serviceDB;
        private SessionManager sessionManager = new SessionManager();
        JsonObject json = new JsonObject();
        private ProgressDialog progress;
        SearchAskService service;

        public SearchAskPresenter(final SearchAskView view) {
            this.searchaskview = view;

            serviceDB = new UsersMySQLiteHelper(AppController.getAppContext());
            service = new SearchAskService(AppController.getAppContext());
            json = SharedPreferenceHelper.getScheduling(AppController.getAppContext());
    /*
            this.searchaskview.getListView().setAdapter(this);
            this.searchaskview.getListView().setOnItemClickListener(this);
    */  
//obtendo o retorno com o Json    
RequestManager.UsersSearchAskTest(json, new FutureCallback<String>() {
                @Override
                public void onCompleted(Exception e, String result) {
                    if (e==null || result!=null){
                        usersSearchList = new Gson().fromJson(new JsonParser().parse(result).getAsJsonObject().get("data").toString(), new TypeToken<ArrayList<SearchAskConstructor>>() {
                        }.getType()); //obtendo o Json

                        if (usersSearchList.size() > 0){
                            notifyDataSetChanged();
                        }
                    }else{
                        Toast.makeText(AppController.getAppContext(),"Não há sugestões",Toast.LENGTH_LONG).show();
                    }
                }
            });
           // usersSearchList = serviceDB.getAllUsers(sessionManager.getLoggedUser().getCompany());
        }

        @Override
        public int getCount() {
            return usersSearchList.size();
        }

        @Override
        public Object getItem(int position) {
            return usersSearchList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            inflater = (LayoutInflater) searchaskview.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            //recupera o estado da posição atual
            final SearchAskConstructor searchUsers = usersSearchList.get(position); //TODO verificar onde pegar as informações de email--etc
            //Cria uma instancia do layout .. na view
            View view = inflater.inflate(R.layout.searchask_item_list, null);
            //loadingStart(true,"Carregando...");
            txt_Email = (TextView) view.findViewById(R.id.txt_email_searchask);
            txt_Nome = (TextView) view.findViewById(R.id.txt_nome_searchask);
            txt_Distance = (TextView) view.findViewById(R.id.txt_distance_searchask);
            btnGo = (ImageButton) view.findViewById(R.id.img_btn_searchask);

            txt_Email.setText(searchUsers.email);
            txt_Distance.setText(String.valueOf(searchUsers.distanceSearch));
            txt_Nome.setText(searchUsers.name);

            btnGo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                 /*   new Routes(searchaskview.getContext())
                            .open(URIs.Chat());*/

                    Intent intent = new Intent(AppController.getAppContext(), SearchAskFinishActivity.class);
                    searchaskview.getActivity().startActivity(intent);

                }
            });

            return view;
        }

I created this class:

public class SearchAskConstructor {
    public int id;
    public String name;
    public String email;
    public String photo_url;
    public int route_id;
    public int user_id;

    public int profile_mode;
    public double distanceSearch;

    public SearchAskConstructor(String name, String photo_url, int profile_mode, int route_id, int user_id, double distance) {
        this.name = name;
        this.photo_url = photo_url;
        this.profile_mode = profile_mode;
        this.route_id = route_id;
        this.user_id = user_id;
        this.distanceSearch = distance;
    }


    public SearchAskConstructor() {
        super();
    }


}

1 answer

1


Simple! First you need to import the following libs, in which it is necessary to work with the classes JSONArray, JSONObject and JSONException, for exceptions treatment. See below:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

Then you can create a new object with a simple string, in this case your JSON. See comments:

try {
    JSONObject myObject = new JSONObject(json);
    JSONArray myArrayData = myObject.getJSONArray("data");

    String distance = null, name = null;
    int id = 0, route_id = 0;

    for (int i = 0; i < myArrayData.length(); i++) {
        JSONObject another_json_object = myArrayData.getJSONObject(i);

        // resgata o id
        id = another_json_object.getInt("id");

        // resgata a distance
        distance = another_json_object.getString("distance");

        // resgata o nome dentro de user
        JSONObject obj = new JSONObject(another_json_object.getString("user"));
        name = obj.getString("name");

        // resgata route_id dentro de ride
        JSONObject obj2 = new JSONObject(another_json_object.getString("ride"));
        route_id = obj2.getInt("route_id");

    }
    // mostra na tela os valores resgatados
    Toast.makeText(this, 
         "name: " + name 
       + "\nid:" + id 
       + "\ndistance:" + distance 
       + "\nroute_id: " + route_id, 
            Toast.LENGTH_SHORT).show();

} catch (JSONException e) {
    e.printStackTrace();
}
  • In this case, I will generate a large load on the customer(celuar) can be various data, gson, It allows me to do something faster, no? Since he brings all this, you did without the need for a FOR.

  • If you are confirming this, how could you not?! What would be the question then? You would have to better detail your question if you wanted to use any specific lib.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.