java json字符串和对象互转
Posted 龙心呢
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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"}]
以上是关于java json字符串和对象互转的主要内容,如果未能解决你的问题,请参考以下文章