Search in sources :

Example 1 with TypeRule

use of org.osgi.util.converter.TypeRule in project felix by apache.

the class JsonSerializerTest method testCodecWithAdapter.

@Test
public void testCodecWithAdapter() throws JSONException {
    Map<String, Foo> m1 = new HashMap<>();
    m1.put("f", new Foo("fofofo"));
    Map<String, Map<String, Foo>> m = new HashMap<>();
    m.put("submap", m1);
    Converter ca = converter.newConverterBuilder().rule(new TypeRule<Foo, String>(Foo.class, String.class, Foo::tsFun)).rule(new TypeRule<String, Foo>(String.class, Foo.class, v -> Foo.fsFun(v))).build();
    JsonSerializerImpl jsonCodec = new JsonSerializerImpl();
    String json = jsonCodec.serialize(m).convertWith(ca).toString();
    JSONObject jo = new JSONObject(json);
    assertEquals(1, jo.length());
    JSONObject jo1 = jo.getJSONObject("submap");
    assertEquals("<fofofo>", jo1.getString("f"));
    // And convert back
    Map<String, Map<String, Foo>> m2 = jsonCodec.deserialize(new TypeReference<Map<String, Map<String, Foo>>>() {
    }).convertWith(ca).from(json);
    assertEquals(m, m2);
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) HashMap(java.util.HashMap) Converter(org.osgi.util.converter.Converter) HashMap(java.util.HashMap) Map(java.util.Map) TypeRule(org.osgi.util.converter.TypeRule) Test(org.junit.Test)

Example 2 with TypeRule

use of org.osgi.util.converter.TypeRule in project felix by apache.

the class YamlSerializerTest method testCodecWithAdapter.

@Test
public void testCodecWithAdapter() {
    Map<String, Foo> m1 = new HashMap<>();
    m1.put("f", new Foo("fofofo"));
    Map<String, Map<String, Foo>> m = new HashMap<>();
    m.put("submap", m1);
    Converter ca = converter.newConverterBuilder().rule(new TypeRule<Foo, String>(Foo.class, String.class, Foo::tsFun)).rule(new TypeRule<String, Foo>(String.class, Foo.class, v -> Foo.fsFun(v))).build();
    YamlSerializerImpl yamlCodec = new YamlSerializerImpl();
    String yaml = yamlCodec.serialize(m).convertWith(ca).toString();
    assertEquals("submap: \n" + "  f: '<fofofo>'", yaml);
    // And convert back
    Map<String, Map<String, Foo>> m2 = yamlCodec.deserialize(new TypeReference<Map<String, Map<String, Foo>>>() {
    }).convertWith(ca).from(yaml);
    assertEquals(m, m2);
}
Also used : HashMap(java.util.HashMap) Converter(org.osgi.util.converter.Converter) Map(java.util.Map) HashMap(java.util.HashMap) TypeRule(org.osgi.util.converter.TypeRule) Test(org.junit.Test)

Aggregations

HashMap (java.util.HashMap)2 Map (java.util.Map)2 Test (org.junit.Test)2 Converter (org.osgi.util.converter.Converter)2 TypeRule (org.osgi.util.converter.TypeRule)2 JSONObject (org.apache.sling.commons.json.JSONObject)1