简体   繁体   中英

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

I have a custom model class like this -

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

My JSON in assets folder is -

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

I need to read and parse this JSON and write it as a list of MyModel object into the shared prefs. To write into prefs, I am doing like this -

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

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

    }

How can I parse this JSON and write it to the prefs as a list of MyModel object?

The JSON is currently stored in my assets folder. Later I can read from the prefs and get the list

It's quite simple:

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

Write this code read JSON from your asset folder.

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

Write this code to read array data from your preference file.

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

firstly load json data from asset folder to string:

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

this method will return the string json file then pass your string json into this:

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

Let's assume that you have data.json file in data folder in your assets.

just try below code to parse your 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));

    }

Here is my logcat result :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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