1

次のコードを参照してください。データのリストをJSON配列にシリアル化する必要があります。

FooEntity.java:

public class FooEntity {

String foo;
String bar;

public String getFoo() {
    return foo;
}

public void setFoo(String foo) {
    this.foo = foo;
}

public String getBar() {
    return bar;
}

public void setBar(String bar) {
    this.bar = bar;
}
}

FooList.java:

public class FooList {
public List<FooEntity> fooList;

public FooList() {
    this.fooList = new ArrayList<FooEntity>();
}

public void add(FooEntity fooEntity) {
    this.fooList.add(fooEntity);
}

public List<FooEntity> getFooList() {
    return fooList;
}

public void setFooList(List<FooEntity> fooList) {
    this.fooList = fooList;
}
}

ここで、FooEntitiesのリストを作成し、JSONにシリアル化します。

public void fooListToJson() throws IOException {
    FooList fooList = new FooList();

    FooEntity fooEntity1 = new FooEntity();
    fooEntity1.setBar("fooEntity1 bar value");
    fooEntity1.setFoo("fooEntity1 foo value");

    FooEntity fooEntity2 = new FooEntity();
    fooEntity2.setBar("fooEntity2 bar value");
    fooEntity2.setFoo("fooEntity2 foo value");

    fooList.add(fooEntity1);
    fooList.add(fooEntity2);

    ObjectMapper mapper = new ObjectMapper();
    StringWriter stringWriter = new StringWriter();
    final JsonGenerator jsonGenerator = mapper.getJsonFactory().createJsonGenerator(stringWriter);

    mapper.writeValue(jsonGenerator, fooList);

    System.out.println(stringWriter.toString());

したがって、出力は次のようになります。

{"fooList":[{"foo":"fooEntity1 foo value","bar":"fooEntity1 bar value"},{"foo":"fooEntity2 foo value","bar":"fooEntity2 bar value"}]}

それはすべて正しいです、私はここにただ1つの必要があります。リストの「ルート」要素を変更する必要があります。現在、ルート要素として「fooList」があります-変​​更する必要があります。

このトピックへのスレッドと投稿はほとんど見つかりませんでしたが、私が望むとおりに機能するものは何もありませんでした。ソリューションは、JSONを対応するJavaクラスに逆シリアル化する可​​能性を維持する必要があります。

4

1 に答える 1

1

@ JsonRootNameは必要なものを提供しますか?

于 2012-12-02T21:39:45.570 に答える