如何用键值格式破坏JSON?

时间:2019-04-29 22:35:56

标签: android json json-deserialization

我正在构建一个应用,该应用使用来自API并具有以下response的某些信息:

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

我的目标是在Recycler View中显示此内容,因此我需要使用相应的值来获取key value(String,DifferentString和WayDifferentString)。如何将这个不好的JSON解析到我的应用中?

4 个答案:

答案 0 :(得分:0)

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;
}
}

答案 1 :(得分:0)

您需要将json转换为Map,然后将Map发送到RecyclerView。如果您不想在RecyclerView中使用地图,则可以将每个地图项目转换为具有属性keyvalue的自定义对象,并将整个地图转换为自定义对象的列表。应该可以。

对于转换,您可以使用GsonMoshi

答案 2 :(得分:0)

有很多方法可以从json格式中获取数据。

1。 使用pojo或模型类

要根据响应创建pojo类,请点击以下链接 :Create Pojo class from response

然后从pojo类中获取并设置数据

  1. 使用json解析

遵循本教程:Json parsing

它为您提供的帮助

如有疑问,请评论我

答案 3 :(得分:0)

尝试这个@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();
        }
    });

    }
 }
}

这是使用键值格式的简单方法。让我知道您是否有任何疑问   与此。