如何从对象创建json-string? –返回空的“ []”?

时间:2018-08-27 23:31:30

标签: java json string object gson

我正在尝试创建make方法,该方法返回一个填充有示例数据的json字符串。我已经创建了一个数据构造器类,但是当我创建数据对象并随后打印它时,由于某种原因,它返回一个空的json:“ []”? 我在这里想念什么?为什么它不返回我刚刚创建的数据对象?

这是我的主要课程:

public class SimulatedDevice {

    public static void printObject(Object object) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gson.toJson(object));
        }


    public static class TelemetryDataPoint {

      public String CreateTelemetryDataPoint() {
        ArrayList<Data.TrendData> trendData = new ArrayList<>();
        trendData.add(new Data.TrendData("Building1", "2018-08-28T01:03:02.997301Z", 2, "occupants", "int"));
        Data data = new Data("B1", "0", "0", trendData);
        printObject(data);
        String json = new Gson().toJson(data);
        return json;
      }

     }
    }

这是我的数据构造函数:

package com.microsoft.docs.iothub.samples;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.sql.Time;
import java.util.ArrayList;
import java.util.List;


public class Data extends ArrayList {
    String Building;
    String Floor;
    String Zone;
    ArrayList<TrendData> Trend;

    public Data(String Building, String Floor, String Zone, ArrayList<TrendData> Trend) {
        this.Building = Building;
        this.Floor = Floor;
        this.Zone = Zone;
        this.Trend = Trend;
}

    public static class TrendData {
        String PointId;
        String Timestamp;
        int Value;
        String Type;
        String Unit;

        public TrendData(String PointId, String Timestamp, int Value, String Type, String Unit) {
            this.PointId = PointId;
            this.Timestamp = Timestamp;
            this.Value = Value;
            this.Type = Type;
            this.Unit = Unit;

        }
    }

1 个答案:

答案 0 :(得分:0)

如果从数据声明中删除“ extends ArrayList”,它将正常工作。我尚未对其进行足够的调试,以弄清楚为什么Gson不喜欢基类为ArrayList。

以下是可能的解释:Trouble with Gson serializing an ArrayList of POJO's

相关问题