java json字符串和对象互转

/**
 * Created by admin on 2017/7/26.
 */
public class NewPost {
    private String title;
    private String content;
    public NewPost(){
    }
    public NewPost(String title,String content){
        setTitle(title);
        setContent(content);
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent(){
        return content;
    }
    public void  setContent(String content){
        this.content=content;
    }
    @Override
    public String toString() {
        return "NewPost{" +
                "title='" + title + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 2017/7/26.
 */
class TestFastjson {
    String json1="[{\"title\":\"post1\",\"content\":\"post1\"},{\"title\":\"post1\",\"content\":\"post1\"}]";
    String json2="{\"title\":\"post1\",\"content\":\"post1\"}";

    public void testFJ(){
        //json字符串转list对象
//        List<NewPost> list= new ArrayList<NewPost>();
        List listpost =JSON.parseObject(json1,List.class);
        System.out.println("listpost    "+listpost);
        //json字符串转对象
        NewPost post =JSON.parseObject(json2,NewPost.class);
        System.out.println("post    "+post);
        //对象转json字符串
        List<NewPost> list= new ArrayList<NewPost>();
        list.add(new NewPost("post1","post1"));
        list.add(new NewPost("post2","post2"));
        String jsonString= JSON.toJSONString(list);
        System.out.println("jsonString     "+jsonString);
    }
    public static void main(String[] args) {
        TestFastjson tf=new TestFastjson();
        tf.testFJ();
    }
}

listpost1    [{"title":"post1","content":"post1"}, {"title":"post1","content":"post1"}]
listpost2    NewPost{title='post1', content='post1'}
jsonString     [{"content":"post1","title":"post1"},{"content":"post2","title":"post2"}]

posted @ 2017-07-26 10:12  龙心呢  阅读(446)  评论(0编辑  收藏  举报