繁体   English   中英

解析 JSON 并将其作为自定义对象列表写入首选项

[英]Parsing JSON and writing it to prefs as a list of custom object

我有一个这样的自定义模型类 -

public class MyModel implements Parcelable {

    String title;
    String message;

    /**
     * Creator method for the Parcel to use.
     */
    public static final Parcelable.Creator<MyModel> CREATOR = new Parcelable.Creator<MyModel>() {

        public MyModel createFromParcel(Parcel source) {
            return new MyModel(source);
        }

        public MyModel[] newArray(int size) {
            return new MyModel[size];
        }
    };

    public void setTitle(final String titleValue) {
        title = titleValue;
    }

    public void setMessage(final String messageValue) {
        message = messageValue;
    }

    public String getTitle() {
        return title;
    }

    public String getMessage() {
        return message;
    }

    public MyModel() {

    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.title);
        dest.writeString(this.message);
    }

    private MyModel(Parcel in) {
        this.title = in.readString();
        this.message = in.readString();
    }
}

我在资产文件夹中的 JSON 是 -

[
  {
    "title": "1",
    "message": "Hi"
  },
  {
    "title": "2",
    "message": "Bye"
  },
  {
    "title": "3",
    "message": "Ciao"
  }
]

我需要读取和解析这个 JSON 并将其作为 MyModel 对象列表写入共享首选项。 要写入首选项,我这样做 -

public void setSteps(final ArrayList<MyModel> steps) {

   Gson gson = new Gson();
   getPrefs(mContext).edit().putString("steps", gson.toJson(steps)).apply();

    }

如何解析此 JSON 并将其作为 MyModel 对象列表写入首选项?

JSON 当前存储在我的资产文件夹中。 稍后我可以从首选项中读取并获取列表

这很简单:

Type listType = new TypeToken<ArrayList<YourClass>>(){}.getType();
List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType);
public ArrayList<MyModel> getSteps(){
    String localData = getPrefs(mContext).getString("steps");
    return new Gson().fromJson(localData , new TypeToken<ArrayList<MyModel>>(){}.getType());
}

编写此代码从您的资产文件夹中读取 JSON。

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("yourfilename.txt");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

编写此代码以从您的首选项文件中读取数组数据。

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
...

String jsonArray = getPrefs(mContext).getString("steps","[]").apply();
Type stepType = new TypeToken<ArrayList<YourModelClass>>(){}.getType();
ArrayList<YourModelClass> yourClassList = new Gson().fromJson(jsonArray, stepType);

首先从资产文件夹加载json数据到字符串:

public String loadJSONFromAsset() {

   // check here data available in pref or not
  //  if available then return string object of pref here else fetch //from asset and set into pref


    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("yourfilename.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

此方法将返回字符串 json 文件,然后将您的字符串 json 传递给:

 Type listType = new TypeToken<ArrayList<ModelClass>>(){}.getType();
    List<ModelClass> yourClassList = new Gson().fromJson(yourJsonString, listType);

假设您的资产中的数据文件夹中有 data.json 文件。

只需尝试以下代码来解析您的 json。

private void getJsonData()
    {
        String json = null;
        try {
            InputStream is = getAssets().open("data/data.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        Type listType = new TypeToken<List<MyModel>>(){}.getType();
        ArrayList<MyModel> steps = new Gson().fromJson(json, listType);
        setSteps(steps);

    }

    public void setSteps(final ArrayList<MyModel> steps) {

        Gson gson = new Gson();
        Log.e("~~~~~", gson.toJson(steps));

    }

这是我的 logcat 结果:

E/~~~~~: [{"message":"Hi","title":"1"},{"message":"Bye","title":"2"},{"message":"Ciao","title":"3"}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM