【问题标题】:How do I create a json-string from object? – It returns an empty "[]"?如何从对象创建 json 字符串? – 它返回一个空的“[]”?
【发布时间】:2018-08-27 23:31:29
【问题描述】:

我正在尝试创建一个方法,该方法返回一个填充有样本数据的 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;

        }
    }

【问题讨论】:

    标签: java json string object gson


    【解决方案1】:

    如果您从数据声明中删除“扩展数组列表”,它将正常工作。我还没有调试到足以弄清楚为什么 Gson 不喜欢基类是 ArrayList。

    这是一个可能的解释:Trouble with Gson serializing an ArrayList of POJO's

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多