简体   繁体   中英

File fields in POJO with json output

I have a POJO in my application:

class Project{
   long id;
   String name;
   File[] images;
   //getter and stter omitted
}

And I use the form to add/update the Project

<form>
  <input name="project.name" .../>
  <input name="project.images[0]  />
  ...
</form>

It works well with CRUD operation exception once I want to get the Project with json format.

I want to get something like this:

{name:"projectname",id:1,images:["http://xx.png","..."]}

But I can not since the images filed have the type of File rather than String .

I can add another fields to hold the image url like this:

class Project{
   long id;
   String name;
   File[] images;
   String[] imageURLs;
   //getter and stter omitted
}

But I am not sure if this is a good idea, since two fields are used to represent the same thing.

I wonder if there is a better alternative solution?

You need a custom deserializer for your File[]. See GSON deserializing key-value to custom object for more details.

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