FastJson-fastjson의 간단한 사용

1623 단어 json
import java.util.ArrayList; import java.util.List;
import com.alibaba.fastjson.JSON;
public class TestFastJson {
/**
 * **java   json   **
 */
public void test1() {
    Group group = new Group();
    group.setId(0L);
    group.setName("admin");

    User guestUser = new User();
    guestUser.setId(2L);
    guestUser.setName("guest");

    User rootUser = new User();
    rootUser.setId(3L);
    rootUser.setName("root");

    group.getUsers().add(guestUser);
    group.getUsers().add(rootUser);

    // **java   json   **
    String jsonString = JSON.toJSONString(group);
    System.out.println(jsonString);
}

/**
 * **json    java  **
 */
public void test2() {
    String json = "{\"id\":0,\"name\":\"admin\","
            + "\"users\":[{\"id\":2,\"name\":\"guest\"},{\"id\":3,\"name\":\"root\"}]}";

    // **json    java  **
    Group group = JSON.parseObject(json, Group.class);
    System.out.println(group.getUsers().get(0).getName());
}

/**
 *   main
 */
public static void main(String[] args) {
    TestFastJson test = new TestFastJson();
    test.test2();
}

}
class User {
private Long id;

private String name;

/**
 *     
 */
public User() {
    super();
}

// getters/setters( )

}
class Group {
private Long id;

private String name;

private List users = new ArrayList();

/**
 *     
 */
public Group() {
    super();
}

// getters/setters( )

}

좋은 웹페이지 즐겨찾기