3

そのJSONを解析する方法:

{
    "foo": {
        "bar": {
            "baz": "Hello"
        },
        "qux": "World"
    }
}

ジャクソンまたはその代替 を使用してそのクラスに:

public class Foo {
    private String baz;
    private String qux;

    public String getBaz() {
        return baz;
    }

    public void setBaz(final String baz) {
        this.baz = baz;
    }

    public String getQux() {
        return qux;
    }

    public void setQux(final String qux) {
        this.qux = qux;
    }
}

次のようなものを期待しています:

@JsonProperty("foo.bar.baz")
private String baz;
@JsonProperty("foo.qux")
private String qux;
4

2 に答える 2

3

この機能はまだJacksonに実装されていないことがわかりました。問題を参照してください。

Foo回避策として、以下のメソッドをクラスに追加できます。

@JsonProperty("foo")
public void setFoo(JsonNode jsonNode) {
    this.qux = jsonNode.get("qux").getTextValue();
    this.baz = jsonNode.get("bar").get("baz").getTextValue();
}
于 2013-03-27T17:08:27.097 に答える
1

注: 私はEclipseLink JAXB(MOXy)のリーダーであり、JAXB(JSR-222)エキスパートグループのメンバーです。

このユースケースはJacksonでは不可能な場合がありますが、MOXyがJSONバインディングプロバイダーとして使用されている場合は可能です。

フー

このユースケースでは、MOXyのパスベースのマッピングを利用できます。

import org.eclipse.persistence.oxm.annotations.XmlPath;

public class Foo {

    private String baz;
    private String qux;

    @XmlPath("foo/bar/baz/text()")
    public String getBaz() {
        return baz;
    }

    public void setBaz(final String baz) {
        this.baz = baz;
    }

    @XmlPath("foo/qux/text()")
    public String getQux() {
        return qux;
    }

    public void setQux(final String qux) {
        this.qux = qux;
    }

}

デモ

JAXBランタイムAPIは、JSONの読み取り/書き込みに使用されます。

import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(2);
        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Foo.class}, properties);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource json = new StreamSource("src/forum15659950/input.json");
        Foo foo = unmarshaller.unmarshal(json, Foo.class).getValue();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(foo, System.out);
    }

}

input.json / Output

{
   "foo" : {
      "bar" : {
         "baz" : "Hello"
      },
      "qux" : "World"
   }
}

詳細については

于 2013-03-28T00:30:25.940 に答える