简体   繁体   中英

How to de-serialize YearMonth with Gson in Android API < 26 / Java 7?

I currently have a response like:

[
  "2017-12",
  "2018-01",
  "2018-02",
  "2018-03"
]

which should be converted to YearMonth . But since Android doesn't support YearMonth until API 26, I can't use it in my app.

I don't need any fancy feature that YearMonth has. All I want is just the ability to de/-serialize from/to String . How can I achieve this?

I'm currently using Gson .

Basically you just should de-/serialize String[] . See below test cases:

@Slf4j
public class YearMonthStringTest {

    public static final String json = 
            "[\n"
            + "  \"2017-12\", \n"
            + "  \"2018-01\", \n"
            + "  \"2018-02\", \n"
            + "  \"2018-03\" \n"
            + "]";

    @Test
    public void fromJsonTest() {
        String[] strs = new Gson().fromJson(json, String[].class);
        Arrays.asList(strs).forEach(str -> {
            log.info("{}", str);
        });
    }

    @Test
    public void toJsonTest() {
        String[] str = new String[] { "2001-01", "1984-02"
                                    , "1878-11", "0000-12" };
        String jsonFromArray = new GsonBuilder()
                .setPrettyPrinting().create().toJson(str);
        log.info("json from array:\n{}", jsonFromArray);
    }

}

YearMonth was introduced in Java 8 so this is more generally Java 7 issue.

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