将JSon格式的"数组"字符串转换为Java对象"数组"。
应用此技术从一个json对象字符串格式中得到一个java对应的对象。
JSONObject是一个“name.values”集合,
通过get(key)方法取得key对应的value部分(字符串)。
通过getJSONObject(key)可以取得一个JSONObject对象。
通过getJSONArray(key)可以得到一个JSONArray对象。
导入需要的jar包:
package com.west.webcourse.po; /** * 第01步:编写bean类, * 下一步com.west.webcourse.servlet.JavaBeanToJOSNString.java */ public class PersonInfoPo { private String name; private int age; private String sex; public PersonInfoPo(){} public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
编写servlet类:
package com.west.webcourse.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.west.webcourse.po.PersonInfoPo; import net.sf.json.JSONArray; public class JavaBeanToJOSNString extends HttpServlet { PersonInfoPo pif = new PersonInfoPo(); PersonInfoPo pif01 = new PersonInfoPo(); /** 第03步:重写doGet()方法,下一步:测试 */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); System.out.println("转换"); out.print("转换后的JSON字符串:<br/>"); /** 向浏览器发送JSon格式的字符串 */ getJsonStringToBeans(); out.flush(); out.close(); } /** 第02步:将JSon类型字符串转换为:po类 */ public void getJsonStringToBeans() { String jsonString = "[{\"name\":\"zhang3\",\"sex\":\"nan\",\"age\":\"30\"},{\"name\":\"zhang4\",\"sex\":\"nan4\",\"age\":\"304\"}]"; System.out.println(jsonString); /*2.1:转换成json数组*/ JSONArray allJsons = JSONArray.fromObject(jsonString); /*2.2:讲json数组转换成PersonInfoPo数组*/ PersonInfoPo[] allBeans = (PersonInfoPo[]) allJsons.toArray(allJsons, PersonInfoPo.class); for (Object object : allBeans) { pif01 = (PersonInfoPo) object; System.out.println("姓名:" + pif01.getName() + ":性别:" + pif01.getSex() + ":年龄:" + pif01.getAge()); } } }
编写测试类:
package com.west.webcourse.servlet; /** * 第04步:测试 * 下一步:配置web.xml */ import org.junit.BeforeClass; import org.junit.Test; public class JavaBeanToJOSNStringTest { static JavaBeanToJOSNString js; @BeforeClass public static void setUpBeforeClass() throws Exception { js=new JavaBeanToJOSNString(); } @Test public void jsonStringToBean() { js.getJsonStringToBeans(); } }
编写po(bean)类:
时间: 2024-10-23 08:06:02