GSON输出为字符串

vatpfxk5  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(280)

我在学习Java的过程中,遇到了使用GSON将String转换为JSON的问题。下面的代码从天气数据库中返回指定的数据,我可以输入这些数据-I目前为止还可以。但是,现在的任务是将输出保存为JSON格式,但这并不起作用。
我很感激任何帮助-谢谢!:)

public static void getInformationFromCity() throws Exception {
    int city = readAndCheckIfCityIsValid();
    System.out.println("input startdate ");
    LocalDate startDate = readAndCheckIfStartDateIsValid();
    System.out.println("input enddate ");
    LocalDate endDate = readAndCheckIfEndDateIsValid();

    List<WeatherData> list = dummy1.getInformationFromCity(city, startDate, endDate);

    System.out.println("\n weatherdata for " + city + " in the timeperiod between" + startDate + " and "
            + endDate + " are:\n");

    for (WeatherData i : list) {

        String output = ("Date: " + i.getLastUpdateTime() + " Temperature: " + i.getCurrentTemperatureCel()
                + "°C" + " , Pressure: " + i.getPressure() + " hPa" + " und humidity: " + i.getHumidity()
                + " %");
        System.out.println(output);

        // to file
        String json = new Gson().toJson(output);

        FileWriter writer = new FileWriter("a02.json");
        writer.write(json);
        writer.close();

    }
}

我的文件中的输出是一个String而不是JSON

  • “日期:2022-02- 03 T23:37:38温度:4.0°C,风压:1023 hPa和湿度:百分之八十三”
qqrboqgw

qqrboqgw1#

编写一个类型适配器和mappingClass:
定义类以Mapjson / gson

class GsonMap{
// define your object
}

定义用于解析LocalTime TypeAdapter

public class GsonParseLocalDateTime extends TypeAdapter<LocalTime>{
    @Override
    public void write(JsonWriter out, LocalTime value) throws IOException {
        // TODO Auto-generated method stub

    }

    @Override
    public LocalTime read(JsonReader in) throws IOException {

        return LocalTime.parse(in.nextString();
    }

}

定义用于解析LocalDateTime TypeAdapter

public class GsonParseLocalTime extends TypeAdapter<LocalDateTime>{
    @Override
    public void write(JsonWriter out, LocalDateTime value) throws IOException {
        // TODO Auto-generated method stub

    }

    @Override
    public LocalDateTime read(JsonReader in) throws IOException {

        return LocalDateTime.parse(in.nextString();
    }

}

创建gson构建器

Gson g = new GsonBuilder()
.registerTypeAdapter(java.time.LocalDateTime.class, new gsonDateTimeParser())
.registerTypeAdapter(java.time.LocalTime.class, new gsonTimeParser())
.create();

Mapjson字符串

g.fromJson(output, GsonMap);

相关问题