版權聲明
轉載請與作者聯繫,轉載時請務必標明文章原始出處和作者信息及本聲明。
|
|
|
微信掃瞄二維碼進入 Netkiller 微信訂閲號 QQ群:128659835 請註明“讀者” |
2017-06-16
Phalcon VS Spring 用法對照表
FYI https://github.com/oscm/shell/blob/master/lang/php/pecl/phalcon.sh
You need to install with compiler, make tools.
#!/bin/sh cd /usr/local/src/ git clone --depth=1 git://github.com/phalcon/cphalcon.git cd cphalcon/build ./install cat > /srv/php/etc/conf.d/phalcon.ini <<EOF extension=phalcon.so EOF
You just only create a file as pom.xml, the maven will be fetch them.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Spring</groupId> <artifactId>Spring</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.1.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.3</version> </dependency> </dependencies> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>
<?php use Phalcon\Mvc\Dispatcher; use Phalcon\Events\Manager as EventsManager; use Phalcon\Logger; try { /** * Read the configuration */ $config = include(__DIR__."/../app/config/config.php"); $loader = new \Phalcon\Loader(); /** * We're a registering a set of directories taken from the configuration file */ $loader->registerDirs( array( $config->application->controllersDir, $config->application->modelsDir, $config->application->formsDir, $config->application->imagesDir, ) )->register(); $loader->registerNamespaces(array( 'Phalcon' => __DIR__.'/../../Library/Phalcon/' )); $loader->register(); /** * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework */ $di = new \Phalcon\DI\FactoryDefault(); $di->set('dispatcher', function() use ($di) { $eventsManager = new EventsManager; $dispatcher = new Dispatcher; $dispatcher->setEventsManager($eventsManager); return $dispatcher; }); /** * The URL component is used to generate all kind of urls in the application */ $di->set('url', function() use ($config) { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri($config->application->baseUri); return $url; }); /** * Setting up the view component */ $di->set('view', function() use ($config) { $view = new \Phalcon\Mvc\View(); $view->setViewsDir($config->application->viewsDir); return $view; }); /** * 資料庫加密key */ $di->set('config', function() use ($config) { return $config; }); /** * Database connection is created based in the parameters defined in the configuration file */ $di->set('db', function() use ($config) { return new \Phalcon\Db\Adapter\Pdo\Mysql(array( "host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname )); }); /** * Start the session the first time some component request the session service */ $di->set('session', function() { $session = new \Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); /* $di->set('session', function() use ($config) { $session = new Phalcon\Session\Adapter\Redis(array( 'path' => sprintf("tcp://%s:%s?weight=1",$config->redis->host, $config->redis->port) )); $session->start(); return $session; }); */ /** * If the configuration specify the use of metadata adapter use it or use memory otherwise */ $di->set('modelsMetadata', function() use ($config) { if (isset($config->models->metadata)) { $metadataAdapter = 'Phalcon\Mvc\Model\Metadata\\'.$config->models->metadata->adapter; return new $metadataAdapter(); } else { return new \Phalcon\Mvc\Model\Metadata\Memory(); } }); /** * If the configuration specify the use of metadata adapter use it or use memory otherwise */ $di->set('modelsManager', function() { return new Phalcon\Mvc\Model\Manager(); }); /** * Handle the request */ $application = new \Phalcon\Mvc\Application(); $application->setDI($di); echo $application->handle()->getContent(); } catch (Phalcon\Exception $e) { echo $e->getMessage(); } catch (PDOException $e){ echo $e->getMessage(); }
WebContent\WEB-INF
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Spring</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>netkiller</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>netkiller</servlet-name> <url-pattern>/welcome.jsp</url-pattern> <url-pattern>/welcome.html</url-pattern> <url-pattern>*.html</url-pattern> </servlet-mapping> </web-app>
netkiller-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="cn.netkiller.controller" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
<?php class IndexController extends ControllerBase { public function indexAction() { } public function welcomeAction() { $message = "Helloworld!!!"; $this->view->setVar('message',$message); } }
package cn.netkiller.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class Welcome { @RequestMapping("/welcome") public ModelAndView helloWorld() { String message = "Helloworld!!!"; return new ModelAndView("welcome", "message", message); } }
http://www.netkiller.cn/news/list/100.html
http://www.netkiller.cn/news/detail/100/1000.html
<?php class NewsController extends \Phalcon\Mvc\Controller { public function listAction($category_id) { $this->view->setVar('category_id',$category_id); } public function detailAction($category_id, $article_id) { $this->view->setVar('category_id',$category_id); $this->view->setVar('article_id',$article_id); } }
package cn.netkiller.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class Pathinfo { @RequestMapping("/news/list/{category_id}") public ModelAndView urlTestId(@PathVariable String category_id) { return new ModelAndView("news/list", "category_id", category_id); } @RequestMapping("/news/detail/{category_id}/{article_id}") public ModelAndView urlTestId(@PathVariable String category_id, @PathVariable String article_id) { ModelMap model = new ModelMap(); model.addAttribute("category_id", category_id); model.addAttribute("article_id", article_id); return new ModelAndView("news/detail", model); } }
http://www.netkiller.cn/member/login?email=netkiller@msn.com
<?php class MemberController extends ControllerBase { public function loginAction() { echo "email=" . $request->get("email"); } }
package cn.netkiller.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class Welcome { @RequestMapping("/member/login") @ResponseBody public String getEmailWithRequestParam(@RequestParam("email") String email) { return "email=" + email; } }
如果參數很多寫起來就非常辛苦
package cn.netkiller.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class Welcome { @RequestMapping("/member/login") @ResponseBody public String getEmailWithRequestParam( @RequestParam("email") String email @RequestParam("password") String password ... ... @RequestParam("ext") String ext ) { ... ... ... } }
<?php class MemberController extends ControllerBase { public function loginAction() { echo "email=" . $request->getPost("email"); echo "password=" . $request->getPost("password"); echo "phone=" . $request->getPost("phone"); } }
package cn.netkiller.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; @Controller public class Member { @RequestMapping("/http/form") public ModelAndView createCustomer(){ ModelMap model = new ModelMap(); model.addAttribute("email", "netkiller@msn.com"); model.addAttribute("phone", "13113668890"); return new ModelAndView("http/form", model); } @RequestMapping(value= "/http/post", method = RequestMethod.POST) public ModelAndView saveCustomer(HttpServletRequest request, @RequestParam(value="Email", required=false) String email, @RequestParam(value="Password", required=false) String password, @RequestParam(value="Phone", required=false) String phone){ ModelMap model = new ModelMap(); model.addAttribute("email", email); model.addAttribute("password", password); model.addAttribute("phone", phone); return new ModelAndView("http/post", model); } }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <?php echo ${message} ?> </body> </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> ${message} </body> </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <?php foreach($books as $book) {?> <?php echo $book ?> <br> <?php } ?> </body> </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <c:forEach items="${books}" var="book"> <c:out value="${book}"></c:out><br> </c:forEach> </body> </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <?php foreach($books as $key=>$value) {?> <?php echo $key ?> : <?php echo $value ?> <br> <?php } ?> </body> </html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <c:forEach items="${books}" var="book"> <c:out value="${book.key}"></c:out> : <c:out value="${book.value}"></c:out> <br> </c:forEach> </body> </html>
<?php use Phalcon\Tag; $this->tag->setDoctype(Tag::HTML401_STRICT); ?> <html> <head> <title>Registration Page</title> </head> <body> <?php = $this->tag->form("products/search") ?> <?php= $this->tag->textField("name") ?> <?php echo $this->tag->passwordField(array("password", "size" => 30)) ?> <?php echo $this->tag->select(array("status", array("A" => "Active","I" => "Inactive")));?> <?php echo $this->tag->textArea(array("aboutYou","","cols" => "6","rows" => 20)) ?> <?php echo $this->tag->hiddenField(array("parent_id","value"=> "5")) ?> <?= $this->tag->submitButton("Register"); ?> <?php = $this->tag->endForm() ?> </body> </html>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head> <title>Registration Page</title> </head> <body> <form:form method="POST" commandName="user"> <form:input path="name" /> <form:password path="password" /> <form:radiobutton path="gender" value="M" label="M" /> <form:radiobutton path="gender" value="F" label="F" /> <form:select path="country"> <form:option value="0" label="Select" /> <form:options items="${countryList}" itemValue="countryId" itemLabel="countryName" /> </form:select> <form:textarea path="aboutYou" /> <form:checkboxes path="communityList" items="${communityList}" itemValue="key" itemLabel="value" /> <form:checkbox path="mailingList" label="Would you like to join our mailinglist?" /> <input type="submit" value="Register"> </form:form> </body> </html>
模型定義
<?php class User extends \Phalcon\Mvc\Model { public function initialize() { } }
在控製器重調用查詢數據
<?php $user = User::find(); print_r($user);
Maven 增加mybatis與mysql依賴設置
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>MyBatis</groupId> <artifactId>MyBatis</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> </dependency> </dependencies> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
mybatis.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 配置資料庫連接信息 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://192.168.6.1:3306/mybatis" /> <property name="username" value="mybatis" /> <property name="password" value="mybatis" /> </dataSource> </environment> </environments> <mappers> <mapper resource="cn/netkiller/mapping/userMapping.xml" /> </mappers> </configuration>
cn/netkiller/mapping/userMapping.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.netkiller.mapping.UserMapping"> <select id="getUser" parameterType="String" resultType="cn.netkiller.model.User"> select * from user where id=#{id} </select> </mapper>
數據類型映射
package cn.netkiller.model; public class User { private String id; private String name; private int age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
測試程序
package cn.netkiller.test; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import cn.netkiller.model.*; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub String resource = "mybatis.xml"; InputStream is = Tests.class.getClassLoader().getResourceAsStream(resource); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession session = sessionFactory.openSession(); String statement = "cn.netkiller.mapping.UserMapping.getUser";// 映射sql的標識字元串 User user = session.selectOne(statement, "2"); System.out.println(user.toString()); } }
<?php use Phalcon\Mvc\Controller; class SessionController extends Controller { public function setAction() { // Set a session variable $this->session->set("username", "netkiller"); } public function getAction() { // Check if the variable is defined if ($this->session->has("username")) { // Retrieve its value echo $this->session->get("username"); } } public function removeAction() { // Remove a session variable $this->session->remove("username"); } public function destroyAction() { // Destroy the whole session $this->session->destroy(); } }
傳統方式
$_SESSION['username'] = "netkiller"; unset($_SESSION['username']);
<dependencies> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session</artifactId> <version>1.0.2.RELEASE</version> </dependency> </dependencies>
package cn.netkiller.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; import cn.netkiller.*; @Controller public class Http { @RequestMapping("/session") @ResponseBody public String home(HttpServletRequest request) { return "" + request.getSession().getCreationTime(); } @RequestMapping("/session/set") @ResponseBody public String setSession(HttpSession session) { String username = "netkiller"; session.setAttribute("username", username); return username; } @RequestMapping("/session/get") @ResponseBody public String getSession(HttpSession session) { String username = (String) session.getAttribute("username"); return username; } @RequestMapping("/session/remove") @ResponseBody public String removeSession(HttpSession session) { session.removeAttribute("username"); String username = (String) session.getAttribute("username"); return username; } @RequestMapping("/session/invalidate") @ResponseBody public String invalidateSession(HttpSession session) { session.invalidate(); return "invalidate"; } }
Servlet 傳統方式
@RequestMapping("/session/Servlet") @ResponseBody public String servletSession(HttpServletRequest request) { String username = "neo"; request.getSession().setAttribute("username", username); return username; }
//Cache arbitrary data $this->cache->save('my-key', array(1, 2, 3, 4, 5)); //Get data $data = $this->cache->get('my-key');
pom.xml
<dependencies> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.1.RELEASE</version> </dependency> </dependencies>
Configure RedisTemplate....
<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:use-pool="true"/> <!-- redis template definition --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="jedisConnFactory"/>
Testing
public class Example { // inject the actual template @Autowired private RedisTemplate<String, String> template; // inject the template as ListOperations // can also inject as Value, Set, ZSet, and HashOperations @Resource(name="redisTemplate") private ListOperations<String, String> listOps; public void addLink(String userId, URL url) { listOps.leftPush(userId, url.toExternalForm()); // or use template directly redisTemplate.boundListOps(userId).leftPush(url.toExternalForm()); } }
$articles = Article::find(array( "cache" => array("service"=> 'redis', "key" => $key, "lifetime" => 60) ));
MyBatis Redis Cache adapter http://mybatis.github.io/redis-cache
pom.xml
<dependencies> <!-- | Provided dependencies --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> <scope>provided</scope> </dependency> <!-- | compile dependencies --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.3</version> <scope>compile</scope> </dependency> </dependencies>
Encode
<?php $json = array( 'contact' => array( 'name' => 'Neo', 'website' => 'http://www.netkiller.cn', 'nickname' => 'netkiller' ) ); print(json_encode($json));
Output
{"contact":{"name":"Neo","website":"http:\/\/www.netkiller.cn","nickname":"netkiller"}}
Decode
<?php $string = '{"contact":{"name":"Neo","website":"http:\/\/www.netkiller.cn","nickname":"netkiller"}}'; print_r(json_decode($string));
輸出
stdClass Object ( [contact] => stdClass Object ( [name] => Neo [website] => http://www.netkiller.cn [nickname] => netkiller ) )
JSON 編碼
package netkiller.json; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.json.*; public final class Writer { public static void main(String[] args) { // TODO Auto-generated method stub JsonObjectBuilder jsonBuilder = Json.createObjectBuilder(); JsonObjectBuilder addressBuilder = Json.createObjectBuilder(); JsonArrayBuilder phoneNumBuilder = Json.createArrayBuilder(); phoneNumBuilder.add("12355566688").add("0755-2222-3333"); addressBuilder.add("street", "Longhua").add("city", "Shenzhen").add("zipcode", 518000); jsonBuilder.add("nickname", "netkiller").add("name", "Neo").add("department", "IT").add("role", "Admin"); jsonBuilder.add("phone", phoneNumBuilder); jsonBuilder.add("address", addressBuilder); JsonObject jsonObject = jsonBuilder.build(); System.out.println(jsonObject); try { // write to file File file = new File("json.txt"); if (!file.exists()) { file.createNewFile(); } OutputStream os = null; os = new FileOutputStream(file); JsonWriter jsonWriter = Json.createWriter(os); jsonWriter.writeObject(jsonObject); jsonWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 運行後輸出 {"nickname":"netkiller","name":"Neo","department":"IT","role":"Admin","phone":["12355566688","0755-2222-3333"],"address":{"street":"Longhua","city":"Shenzhen","zipcode":"518000"}}
JSON 解碼
package netkiller.json; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonValue; public final class Reader { public static final String JSON_FILE="json.txt"; public static void main(String[] args) throws IOException { InputStream fis = new FileInputStream(JSON_FILE); //create JsonReader object JsonReader jsonReader = Json.createReader(fis); //get JsonObject from JsonReader JsonObject jsonObject = jsonReader.readObject(); //we can close IO resource and JsonReader now jsonReader.close(); fis.close(); System.out.printf("nickname: %s \n", jsonObject.getString("nickname")); System.out.printf("name: %s \n", jsonObject.getString("name")); System.out.printf("department: %s \n", jsonObject.getString("department")); System.out.printf("role: %s \n", jsonObject.getString("role")); JsonArray jsonArray = jsonObject.getJsonArray("phone"); //long[] numbers = new long[jsonArray.size()]; int index = 0; for(JsonValue value : jsonArray){ //numbers[index++] = Long.parseLong(value.toString()); System.out.printf("phone[%d]: %s \n", index++, value.toString()); } //reading inner object from json object JsonObject innerJsonObject = jsonObject.getJsonObject("address"); System.out.printf("address: %s, %s, %d \n", innerJsonObject.getString("street"), innerJsonObject.getString("city"), innerJsonObject.getInt("zipcode")); } } 運行結果 nickname: netkiller name: Neo department: IT role: Admin phone[0]: +8612355566688 phone[1]: 0755-2222-3333 address: Longhua, Shenzhen, 518000