码迷,mamicode.com
首页 > 编程语言 > 详细

java json字符串和对象互转

时间:2017-07-26 10:39:18      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:pos   lib   class   code   tostring   iba   log   ati   dmi   

/**
 * 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"}]

java json字符串和对象互转

标签:pos   lib   class   code   tostring   iba   log   ati   dmi   

原文地址:http://www.cnblogs.com/imtester/p/7238093.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!