简体   繁体   English

我需要使用GSON将图像数组解析为json

[英]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 当解析为json时,我需要获取

"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 但是当解析时,“ document_photos []”为空

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. build.gradle Gson库添加为依赖项。

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

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