一  json -> entity

User.java

package com.xxx.hotel.train.json.json2entity;

import java.io.Serializable;

/**
 * @author balfish
 * @date 15-7-22
 */
public class User implements Serializable {
    private static final long serialVersionUID = 5483047693755054496L;

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

Json2EntityTest.java

package com.xxx.hotel.train.json.json2entity;

import net.sf.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author balfish
 * @date 15-7-22
 */
public class Json2EntityTest {

    // json转化为entity,list和map同理,此处不作累述
    private static ObjectMapper objectMapper = null;

    public static void main(String[] args) throws Exception{
        objectMapper = new ObjectMapper();
        writeJson2Entity();
    }

    private static void writeJson2Entity() throws Exception {
        String json = "{ \"username\":\"balfish\" , \"password\":\"balfish\"}";
        System.out.println(objectMapper.readValue(json, User.class));

        JSONObject jsonObject = JSONObject.fromObject(json);
        System.out.println(jsonObject);
    }

}

二  entity -> json

User.java

package com.xxx.hotel.train.json.entity2json;

import java.io.Serializable;

/**
 * @author balfish
 * @date 15-7-22
 */
public class User implements Serializable {
    private static final long serialVersionUID = 359755144270845410L;
    private String username;
    private String password;
    private Car car;

    public User(String username, String password, Car car) {
        this.username = username;
        this.password = password;
        this.car = car;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    @Override
    public String toString() {
        return "User{" +
                "car=" + car +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

Car.java

package com.xxx.hotel.train.json.entity2json;

import java.io.Serializable;

/**
 * @author balfish
 * @date 15-7-22
 */
public class Car implements Serializable {

    private static final long serialVersionUID = -1013056738822619070L;
    private String color;
    private String country;

    public Car(String color, String country) {
        this.color = color;
        this.country = country;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Override
    public String toString() {
        return "Car{" +
                "color='" + color + '\'' +
                ", country='" + country + '\'' +
                '}';
    }
}

Entity2JsonTest.java

package com.xxx.hotel.train.json.entity2json;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * @author balfish
 * @date 15-7-22
 */
public class Entity2JsonTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(Entity2JsonTest.class);
    private static ObjectMapper objectMapper = null;
    private static User user = null;

    private static void writeEntity2Json() throws IOException {
        /**
         * 小心 objectMapper.writeValue(System.out, user); 这个方法只会打印一次结果 因为在这个重载方法中在向控制台进行重定向以后会有一个流关闭的过程,那么将无法继续写入 所以慎用
         */
        System.out.println("用objectMapper的方法......(entity->json)");
        System.out.println(objectMapper.writeValueAsString(user));
    }

    private static void writeList2Json() throws IOException {
        System.out.println("用objectMapper的方法......(list->json)");
        List<User> userList = Lists.newArrayList();
        userList.add(user);

        User user = new User("sam", "sam", new Car("green", "England"));
        userList.add(user);
        System.out.println(objectMapper.writeValueAsString(userList));

        System.out.println("用JsonArray的方法......(list->json)");
        List<Object> list = Lists.newArrayList();
        list.add(1);
        list.add(true);
        list.add('j');
        list.add(new char[] { 'j', 's', 'o', 'n' });
        list.add(null);
        list.add("json");
        list.add(new String[] { "json", "-", "lib" });

        System.out.println(JSONArray.fromObject(list));
    }

    private static void writeMap2Json() throws IOException {
        /**
         * objectMapper.writeValue(new File("/home/balfish/jsonmap.txt"), stringObjectMap);
         * 如上,wtiteValue有很多重载方法,可以根据需要选择
         */
        System.out.println("用objectMapper的方法......(map->json)");
        Map<String, Object> stringObjectMap = Maps.newLinkedHashMap();

        stringObjectMap.put("username", user.getUsername());
        stringObjectMap.put("password", user.getPassword());
        stringObjectMap.put("user", user);
        System.out.println(objectMapper.writeValueAsString(stringObjectMap));

        /**
         * 这里的map如果key不是string的话,会报错如下 Exception in thread "main" net.sf.json.JSONException:
         * java.lang.ClassCastException: JSON keys must be strings.
         */
        System.out.println("用JSONObject的方法......(map->json)");
        Map<String, Object> map = Maps.newLinkedHashMap();
        map.put("1", "Beijing");
        map.put("2", "Shanghai");
        /**
         * JSONObject的fromObject方法   {"1":"Beijing","2":"Shanghai"}
         * JSONArray 的fromObject方法  [{"1":"Beijing","2":"Shanghai"}]
         * 区别目前来看在于那个中括号
         */
        System.out.println(JSONObject.fromObject(map));
    }

    public static void main(String[] args) {
        user = new User("balfish", "balfish", new Car("red", "China"));
        objectMapper = new ObjectMapper();
        try {
            writeEntity2Json();
            writeList2Json();
            writeMap2Json();
        } catch (IOException e) {
            LOGGER.error("(entity/list/map)转换成json时出错", e);
        }
    }
}

三 需要的额外maven依赖包

   <!-- json-lib -->
      <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>

   <!-- Jackson mapper -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

json 与entity/list/map的转换的更多相关文章

  1. 用jackson包实现json、对象、Map之间的转换

    jackson API的使用 用jackson包实现json.对象.Map之间的转换

  2. java json与map互相转换(二)

      java json与map互相转换(二) CreationTime--2018年7月16日15点09分 Author:Marydon 1.准备工作 所需jar包: commons-beanutil ...

  3. java json与map互相转换(一)

      java json与map互相转换(一) CreationTime--2018年7月16日 Author:Marydon 1.准备工作 所需jar包:json-20180130.jar impor ...

  4. java中 json和bean list map之间的互相转换总结

    JSON 与 对象 .集合 之间的转换 JSON字符串和java对象的互转[json-lib]   在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML.JSON等,JSON作为一个轻量级 ...

  5. 在js中将map对象转换成json 和 js对cookie的操作

    在js中将map对象转换成json //msp转objectlet obj= Object.create(null); for (let[k,v] of map) { obj[k] = v; }//o ...

  6. C++实现json字符串与map的转换

    开源资源库 jsoncpp-src-0.5.0.tar.gz:https://sourceforge.net/projects/jsoncpp/ jsoncpp-master.ziphttps://g ...

  7. ES6中Json、String、Map、Object之间的转换

    /** *字符串转json * */ static stringToJson(data){ return JSON.parse(data); } /** *json转字符串 */ static jso ...

  8. Json,String,Map之间的转换

    前提是String的格式是map或json类型的 String 转Json JSONObject  jasonObject = JSONObject.fromObject(str); String 转 ...

  9. fastjson将json字符串转化成map的五种方法

    package com.zkn.newlearn.json; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObj ...

随机推荐

  1. 调用ZoomEye API获取信息

    最近在提高自己编程能力,拿一些实用的小工具练下.该脚本为python语言,主要涉及模块urllib,json,os模块. 功能:调用ZoomEye API获取信息 import urllib.requ ...

  2. .net C# 苹果消息推送 工具类

    public class AppleAPNSMessage { /// <summary> /// 苹果信息推送 证书 路径(注意测试版跟正式发布版证书上不一样) /// </sum ...

  3. docker openvswitch网络方案

    1. 测试环境 75机(10.11.150.75):Red Hat Enterprise Linux Server 7.0,无外网访问权限,已安装Docker Server 74机(10.11.150 ...

  4. 2.1 IDEA

    1.背景:IntelliJ IDEA 比 Eclipse 更好http://www.oschina.net/news/26929/why-intellij-is-better-than-eclipse ...

  5. Arpa's weak amphitheater and Mehrdad's valuable Hoses

    Arpa's weak amphitheater and Mehrdad's valuable Hoses time limit per test 1 second memory limit per ...

  6. mysql 查询语句

    查询一段时间到另一段时间的数据 $from=$_POST['from']; $to=$_POST['to']; $query_xiangmu ="SELECT * FROM yichang ...

  7. mysql B+树 Cardinality MRR

    B+树索引并不能找到一个给定键值的具体行,而是被查找数据行所在的页.然后数据库通过把页读入到内存,再在内存中进行查找,最后得到想要查找的数据. Show index from table. Cardi ...

  8. 用PHP提取MYSQL二进制日志的SQL语句

    上一篇说道,在从日志提取出SQL语句的时候,碰到了一句SQL跨了N行无法提取.后来在网上搜了两句shell: sed -n '/^INSERT /,/;/p' log.sql > log_ins ...

  9. ActionBar之style出现Cannot resolve symbol 'Theme' 错误

    今天 2014/03/08 00:49 刚刚升级 android studio 到了 0.5.0 版本,修复了许多 bug,包含当前这个问题,之前一直困扰我很久,莫名奇妙的提示主题样式找不到,无法解析 ...

  10. How to solve java.net.SocketTimeoutException:60000millis problem in HDFS

    Many HDFS users encounter the following error when DFSClient ready file from a certain Data Node.  & ...