rkovtiuk
rkovtiuk

Reputation: 32

I need to parse images array to json with GSON

The method where I get the images

private List<HashMap<String, RequestBody>> getUserDocumentsPhoto(File[] images){

    HashMap<String, RequestBody> userDocumentsPhoto = new HashMap<>();
    List<HashMap<String, RequestBody>> photos = new ArrayList<>();

    for (File image : images) {
        RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), image);
        userDocumentsPhoto.put("filename=\"" + image.getName(), fileBody);
    }
    photos.add(userDocumentsPhoto);
    return photos;

When parse to json I need to get

"document_photos": [
"/system/attachments/files/000/000/110/original/photo20160726_120701-1392731703.jpg?1469524104",
"/system/attachments/files/000/000/111/original/photo20160726_120814-2041790628.jpg?1469524105"]

But when it parsed, "document_photos []" has null

Upvotes: 1

Views: 1474

Answers (1)

Gunay Abdullayeva
Gunay Abdullayeva

Reputation: 711

You must create model class. Which the structure of this class is like this:

public class Model {
    ArrayList<String> items = new ArrayList<>();

    public ArrayList<String> getItems() {
        return items;
    }

    public void setItems(ArrayList<String> items) {
        this.items = items;
    }
}

and your activity like this:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Model model = new Model();
        model.getItems().add("first");
        model.getItems().add("second");
        Gson gson = new Gson();
        String json = gson.toJson(model);
        Log.e("json",json);
    }
}

Add Gson library in your build.gradle as dependency.

Upvotes: 2

Related Questions