Example #1
0
  @Test
  public void testRuntimeSerialization() {
    Book book = new Book();
    book.setPrice(10.0);
    book.setId(331);
    book.setText("very good");
    book.setSell(true);
    book.setTitle("gook book");
    System.out.println(Json.toJson(book));

    TestBook t = new TestBook();
    t.setObj(new Object());
    t.setBook(book);
    String t0 = Json.toJson(t);
    JsonObject o = Json.toJsonObject(t0);
    Assert.assertThat(o.getJsonObject("book").getInteger("id"), is(331));
    Assert.assertThat(o.getJsonObject("obj"), nullValue());

    t = new TestBook();
    t.setObj(book);
    t.setBook(book);
    String t1 = Json.toJson(t);
    o = Json.toJsonObject(t1);
    Assert.assertThat(o.getJsonObject("book").getInteger("id"), is(331));
    Assert.assertThat(o.getJsonObject("obj").getInteger("id"), is(331));

    t.setObj(new Object());
    String t2 = Json.toJson(t);
    o = Json.toJsonObject(t2);
    Assert.assertThat(o.getJsonObject("book").getInteger("id"), is(331));
    Assert.assertThat(o.getJsonObject("obj"), nullValue());

    t.setObj(book);
    String t3 = Json.toJson(t);
    o = Json.toJsonObject(t3);
    Assert.assertThat(o.getJsonObject("book").getInteger("id"), is(331));
    Assert.assertThat(o.getJsonObject("obj").getInteger("id"), is(331));

    TestBook2<Book> tb2 = new TestBook2<Book>();
    tb2.setObj(book);
    tb2.setBook(null);
    String t4 = Json.toJson(tb2);
    o = Json.toJsonObject(t4);
    Assert.assertThat(o.getJsonObject("book"), nullValue());
    Assert.assertThat(o.getJsonObject("obj").getInteger("id"), is(331));

    tb2.setObj(book);
    String t5 = Json.toJson(tb2);
    o = Json.toJsonObject(t5);
    Assert.assertThat(o.getJsonObject("book"), nullValue());
    Assert.assertThat(o.getJsonObject("obj").getInteger("id"), is(331));

    TestBook2<Object> tb3 = new TestBook2<Object>();
    tb3.setObj(book);
    tb3.setBook(book);
    String t6 = Json.toJson(tb3);
    o = Json.toJsonObject(t6);
    Assert.assertThat(o.getJsonObject("book").getInteger("id"), is(331));
    Assert.assertThat(o.getJsonObject("obj").getInteger("id"), is(331));
  }
Example #2
0
  @Test
  public void test4() {
    SimpleObj2 so2 = new SimpleObj2();
    so2.setId(334);

    User user = new User();
    user.setId(2434L);
    user.setName("Pengtao");
    so2.setUser(user);

    Book book = new Book();
    book.setId(23424);
    book.setPrice(3.4);
    book.setSell(true);
    book.setText("cccccccc");
    book.setTitle("ddddd");
    so2.setBook(book);

    String jsonStr = Json.toJson(so2);

    SimpleObj2 temp = Json.toObject(jsonStr, SimpleObj2.class);
    Assert.assertThat(temp.getBook().getPrice(), is(3.4));
    Assert.assertThat(temp.getBook().getTitle(), nullValue());
    Assert.assertThat(temp.getId(), is(334));
  }