Как разбить JSON с форматом ключ-значение? - PullRequest
0 голосов
/ 30 апреля 2019

Я создаю приложение, которое потребляет некоторую информацию из API, которое имеет следующее response:

"something": {
    "String": 2,
    "DifferentString": 4,
    "WayDifferentString": 10
   }

Моя цель - показать это в Recycler View, поэтому мне нужно извлечь key value (String, DifferentString и WayDifferentString) с соответствующим значением. Как я могу разобрать этот плохой JSON в моем приложении?

Ответы [ 4 ]

0 голосов
/ 30 апреля 2019

Попробуйте это @ Jsoe,

StringRequest stringRequest = new StringRequest(url , new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {
                JsonObject object = new JsonObject(response);
                String something = object.getString("something");
                JsonObject jsonObject = new JsonObject(something);

                ArrayList<Hashmap<String,String>> arraylist = new ArrayList<>();

                for(int i= 0 ; i < jsonObject.length ; i++){

                 HashMap<String, String> hashMap = new HashMap<>();

                 String firstString = jsonObject.getString("String");
                 String differentString = jsonObject.getString("DifferentString");
                 String wayDifferentString = 
                              jsonObject,getString("WayDifferentString");

                 hashMap.put("firstString ", firstString);
                 hashMap.put("differentString", differentString); 
                 hashMap.put("wayDifferentString", wayDifferentString); 
                 arraylist.add(hashMap);

                 }

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


        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    RequestQueue queue = Volley.newRequestQueue(this);
    queue.add(stringRequest);

 //setting adapter data to the RecyclerView
private void attachAdapter(ArrayList<HashMap<String, String>> 
arrayList) {

ExampleAdapter adapter = new ExampleAdapter(arrayList,this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}

Адаптер layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/firstString"
/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/differentString"
/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/WayDifferentString"
/>

Код адаптера:

public class ExampleAdpater extends 
    RecyclerView.Adapter<ExampleAdpater.ExampleViewHolder>{

public ArrayList<HashMap<String,String>> arraylist;

public Context context;

public ExampleAdpater(ArrayList<HashMap<String, String>> arraylist, Context context) 
{
this.arraylist= arraylist;
this.context = context;
 }

@NonNull
@Override
public ExampleViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = 
 LayoutInflater.from(viewGroup.getContext()).
                           inflate(R.layout.textLayout,viewGroup,false);
return new ExampleViewHolder(view);
}

 @Override
 public void onBindViewHolder(@NonNull ExampleViewHolder viewHolder, int i) {

 HashMap<String,String> hashMap = arraylist.get(i);
 viewHolder.name.setText(hashMap.get("firstString"));
 viewHolder.tid.setText(hashMap.get("differentString"));
 viewHolder.tid.setText(hashMap.get("wayDifferentString"));

 }

 @Override
 public int getItemCount() {
  return arraylist.size();
 }

 public class ExampleViewHolder extends RecyclerView.ViewHolder{

TextView string,differentString,wayDifferentString;

public ExampleViewHolder(@NonNull View itemView) {
    super(itemView);

    string = itemView.findViewById(R.id.string);
    differentString = itemView.findViewById(R.id.differentString);
    wayDifferentString = itemView.findViewById(R.id.differentString);

    wayDifferentString.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(v.getContext(), 
                    ""+wayDifferentString.getText().toString(), 
      Toast.LENGTH_SHORT).show();
        }
    });

    }
 }
}

Этопростой способ использовать формат ключ-значение.Сообщите мне, если у вас есть какие-либо вопросы с этим.

0 голосов
/ 30 апреля 2019

Вам необходимо преобразовать JSON в карту, а затем отправить карту в RecyclerView.Если вы не хотите использовать карту с вашим RecyclerView, вы можете преобразовать каждый элемент карты в пользовательский объект со свойствами key и value и преобразовать всю карту в список вашего пользовательского объекта.Это должно работать.

Для преобразования вы можете использовать Gson или Moshi

0 голосов
/ 30 апреля 2019

Есть много способов извлечь данные из формата json.

1.используя pojo или класс модели

для создания класса pojo из ответа, перейдите по следующей ссылке: Создайте класс Pojo из ответа

, затем получите и установите данные из класса pojo

с использованием анализа json

следуйте этому руководству: Анализ Json

его помощь для вас

если какой-либо запрос, пожалуйста, прокомментируйте меня

0 голосов
/ 30 апреля 2019

1 - добавьте этот класс в ваш проект:

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

class HandlerHttp {

HandlerHttp() {
}

String makeServiceCall(final String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(MainActivity.TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(MainActivity.TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(MainActivity.TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(MainActivity.TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(final InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
}

2 - получите данные из json, затем добавьте в RecyclerView:

HandlerHttp sh = new HandlerHttp();
        final String jsonURL = "YOUR JSON URL";
        final String ServiceCall = sh.makeServiceCall(jsonURL);

        if(ServiceCall != null){
            try{
                JSONObject jsonObj = new JSONObject(ServiceCall);
                JSONObject something = jsonObj.getJSONObject("something");
                String stringName = something.getString("String");
                String DifferentString = something.getString("DifferentString");
                String WayDifferentString = something.getString("WayDifferentString");

                //then add to your adapter
                //example:

                ListData.add(new ExampleModel(stringName, DifferentString, WayDifferentString));
                //add to your recyclerView
                YourAdapter adapter = new YourAdapter(MainActivity.this, ListData);
                your_recyclerView.setAdapter(adapter);

            }catch (Exception e){
                //
            }
        }

ваш формат json должен выглядеть следующим образом:

"something": 
{
"String": "2",
"DifferentString": "4",
"WayDifferentString": "10"
}

ваш класс Model должен быть таким:

public class ExampleModel {

private String StringName;
private String DifferentString;
private String WayDifferentString;

public ExampleModel(String stringName, String differentString, String wayDifferentString) {
    StringName = stringName;
    DifferentString = differentString;
    WayDifferentString = wayDifferentString;
}

public String getStringName() {
    return StringName;
}

public void setStringName(String stringName) {
    StringName = stringName;
}

public String getDifferentString() {
    return DifferentString;
}

public void setDifferentString(String differentString) {
    DifferentString = differentString;
}

public String getWayDifferentString() {
    return WayDifferentString;
}

public void setWayDifferentString(String wayDifferentString) {
    WayDifferentString = wayDifferentString;
}
}
...