-
2021-03-06 23:20:55
package com.cjonline.foundation.util;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
public class JsonUtils {
/** 默认的字符串格式 */
private static String dateformat = "yyyy-MM-dd hh:mm:ss";
/**
* 获取日期字符串格式
*
* @return
*/
public static String getDateformat() {
return dateformat;
}
/**
* 设置日期字符串格式
*
* @param dateformat
*/
public void setDateformat(String dateformat) {
JsonUtils.dateformat = dateformat;
}
/**
* 获取实体bean的属性返回类型
*
* @param typeName
* 类型名称
* @param fieldValue
* 字段值
* @return
*/
private static Object toType(Object fieldValue) {
Object result = "";
if (fieldValue instanceof String) {
String value = (String) fieldValue;
if (value.contains("\r\n")) {
value = value.replaceAll("\r\n", "\\\\r\\\\n");
}
result = "\"" + value + "\"";
} else if (fieldValue instanceof Number) {
result = fieldValue;
} else if (fieldValue instanceof Boolean) {
result = fieldValue;
} else if (fieldValue instanceof BigDecimal) {
result = fieldValue;
} else if (fieldValue instanceof Date) {
SimpleDateFormat sdf = new SimpleDateFormat(getDateformat());
result = "\"" + sdf.format(fieldValue) + "\"";
} else {
result = "\"" + "\"";
;
}
return result;
}
/**
* 是将单个实体bean的格式化为json字符串
*
* @param obj
* 实体bean
* @return json字符串
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws Exception
*/
public static String Object2JSON(Object obj, Object[] showfields) {
StringBuffer sb = new StringBuffer();
sb.append("{");
if (obj == null) {
return sb.append("}").toString();
}
Field[] fds = obj.getClass().getDeclaredFields();
for (int i = 0; i < fds.length; i++) {
fds[i].setAccessible(true);
String fieldName = fds[i].getName();
Object fieldValue = null;
try {
fieldValue = fds[i].get(obj);
} catch (Exception e) {
e.printStackTrace();
}
if (showfields == null) {
sb.append("\"" + fieldName + "\"").append(":");
sb.append(toType(fieldValue)).append(",");
} else {
for (Object showfield : showfields) {
if (showfield instanceof String) {
if (fieldName.equalsIgnoreCase((String) showfield)) {
sb.append("\"" + fieldName + "\"").append(":");
sb.append(toType(fieldValue)).append(",");
}
}
}
}
}
String result = "";
if (sb.toString().length() == 1) {
result = "{";
} else {
result = sb.substring(0, sb.length() - 1);
}
return result + "}";
}
/** * 可以对多个实体bean的集合操作,输出的是grid的格式 * * @param obj * 可以使实体bean的集合或个体 * @param showfields * 需要显示的字段 * @return * @throws Exception */ public static String ListObject2JSON(Object obj, Object[] showfields) throws Exception { StringBuffer sb = new StringBuffer(); StringBuffer rows = new StringBuffer(); sb.append("["); if (obj instanceof Collection) { @SuppressWarnings("rawtypes") Collection cc = (Collection) obj; if (cc.size() < 1) { return sb.append("]").toString(); } Object[] objects = cc.toArray(); for (Object object : objects) { rows.append(Object2JSON(object, showfields)).append(","); } rows = rows.replace(rows.length() - 1, rows.length(), ""); } sb.append(rows).append("]"); return sb.toString(); } }
更多相关内容 -
JS如何把字符串转换成json
2020-11-21 04:01:45这篇文章主要介绍了JS如何把字符串转换成json,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Json格式字符串 "{"rows":[{"date":"2018-11-19","money":"22",... -
Java将Date日期类型字段转换成json字符串的方法
2021-02-26 14:46:10但是,如果我们将数据转换成json格式的时候,我们也许会遇到date日期型的数据转换成json格式后,并不是我们想要的格式。下面我们通过简单的demo来说明这个问题。我们按照一般json格式生成,会出现以下问题:采用json...想必我们在做项目的时候,都会遇到服务端与客户端交互数据。一般情况下我们都会采用json格式或者xml格式,将服务端的数据转换成这两种格式之一。
但是,如果我们将数据转换成json格式的时候,我们也许会遇到date日期型的数据转换成json格式后,并不是我们想要的格式。下面我们通过简单的demo
来说明这个问题。
我们按照一般json格式生成,会出现以下问题:
采用json:将数据生成json格式,需要导入相应的jar包,如下图:
student.java
package com.xbmu.bean;
import java.io.serializable;
import java.util.date;
public class student implements serializable {
private string username;
private date birthday;
public student() {
super();
// todo auto-generated constructor stub
}
public student(string username, date birthday) {
super();
this.username = username;
this.birthday = birthday;
}
public string getusername() {
return username;
}
public void setusername(string username) {
this.username = username;
}
public date getbirthday() {
return birthday;
}
public void setbirthday(date birthday) {
this.birthday = birthday;
}
@override
public string tostring() {
return "student [username=" + username + ", birthday=" + birthday + "]";
}
}
testdatevaluetojson.java
package com.xbmu.test;
import java.util.arraylist;
import java.util.date;
import java.util.list;
import net.sf.json.jsonarray;
import com.xbmu.bean.student;
public class testdatevaluetojson {
public static void main(string[] args) {
/**
* 创建三个student对象,并将对象添加到list集合中
*
* */
list list = new arraylist();
student student = new student("张三", new date());
list.add(student);
student = new student("李四",new date());
list.add(student);
student = new student("王五",new date());
list.add(student);
/**将list集合众的数据转换成json格式的字符串形式*/
jsonarray array = new jsonarray();
array = array.fromobject(list);
system.out.println(array.tostring());
运行java应用程序,看见在控制台是哪个打印出了:(这里通过json格式化工具处理后了,方便大家阅读)
[
{
"birthday": {
"date": 3,
"day": 4,
"hours": 9,
"minutes": 5,
"month": 11,
"seconds": 1,
"time": 1449104701018,
"timezoneoffset": -480,
"year": 115
},
"username": "张三"
},
{
"birthday": {
"date": 3,
"day": 4,
"hours": 9,
"minutes": 5,
"month": 11,
"seconds": 1,
"time": 1449104701018,
"timezoneoffset": -480,
"year": 115
},
"username": "李四"
},
{
"birthday": {
"date": 3,
"day": 4,
"hours": 9,
"minutes": 5,
"month": 11,
"seconds": 1,
"time": 1449104701018,
"timezoneoffset": -480,
"year": 115
},
"username": "王五"
}
]
虽然符合json语法格式,但是里面的birthday字段是日期型的,并不是我们一般情况下需要的。这时候,我们就必须写一个工具类进行处理了。
但遇到date类型的数据的时候,就需要进行处理。
package com.xbmu.utils;
import java.text.simpledateformat;
import java.util.date;
import java.util.locale;
import net.sf.json.jsonconfig;
import net.sf.json.processors.jsonvalueprocessor;
/**
* 自定义jsonvalueprocessor
* 比如我们要控制json序列化过程中的date对象的格式化,以及数值的格式化,jsonvalueprocessor是最好的选择。
* @author bitaotao
*
*/
public class jsondatevalueprocessor implements jsonvalueprocessor {
private string pattern = "yyyy-mm-dd";
public object processarrayvalue(object value, jsonconfig config) {
return process(value);
}
public object processobjectvalue(string key, object value, jsonconfig config) {
return process(value);
}
private object process(object value){
if(value instanceof date){
simpledateformat sdf = new simpledateformat(pattern, locale.uk);
return sdf.format(value);
}
return value == null ? "" : value.tostring();
}
}
除了自定义日期格式外,还可以如法炮制,控制数值格式化、html内容转码等。
testdatevaluetojson.java
package com.xbmu.test;
import java.util.arraylist;
import java.util.date;
import java.util.list;
import net.sf.json.jsonarray;
import net.sf.json.jsonconfig;
import com.xbmu.bean.student;
import com.xbmu.utils.jsondatevalueprocessor;
public class testdatevaluetojson {
public static void main(string[] args) {
/**
* 创建三个student对象,并将对象添加到list集合中
*
* */
list list = new arraylist();
student student = new student("张三", new date());
list.add(student);
student = new student("李四",new date());
list.add(student);
student = new student("王五",new date());
list.add(student);
/**将list集合众的数据转换成json格式的字符串形式*/
jsonconfig config = new jsonconfig();
jsondatevalueprocessor jsonvalueprocessor = new jsondatevalueprocessor();
config.registerjsonvalueprocessor(date.class, jsonvalueprocessor);
jsonarray array = new jsonarray();
array = array.fromobject(list,config);
system.out.println(array.tostring());
}
}
运行java应用程序,会得到我们期望的json格式:
[
{
"birthday": "2015-12-03",
"username": "张三"
},
{
"birthday": "2015-12-03",
"username": "李四"
},
{
"birthday": "2015-12-03",
"username": "王五"
}
]
很显然这种日期格式,是我们经常使用的。也方便在客户端解析这种格式的json字符串。
总结
到此这篇关于java将date日期类型字段转换成json字符串的文章就介绍到这了,更多相关java date日期类型字段转json字符串内容请搜索萬仟网以前的文章或继续浏览下面的相关文章希望大家以后多多支持萬仟网!
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!
-
js中将字符串转换成json的三种方式
2020-12-03 16:06:06ECMA-262(E3) 中没有将JSON概念写到标准中,还好在 ECMA-262(E5) 中JSON的概念被正式引入了,包括全局的JSON对象和Date的toJSON方法。 1,eval方式解析,恐怕这是最早的解析方式了。如下: 代码如下: function str... -
JSON五:Java:对象转换成JSON字符串;JSON字符串转换为对象;
2021-01-10 18:07:21一:将对象转换成JSON字符串(序列化) 一:附:@JSONField注解 二:将JSON字符串转换为对象(反序列化) 主要内容是Java中的利用FastJson对JSON的序列化与反序列化。 一:将对象转换成JSON字符串(序列化) ...目录
主要内容是Java中的利用FastJson对JSON的序列化与反序列化。
一:将对象转换成JSON字符串(序列化)
示例一:将对象转换成JSON字符串
javaBean:
import java.util.Date; public class Employee { private Integer empno; private String ename; private String job; private Date hdate; private Float salary; private String dname; public Employee() {} public Employee(Integer empno, String ename, String job, Date hdate, Float salary, String dname) { super(); this.empno = empno; this.ename = ename; this.job = job; this.hdate = hdate; this.salary = salary; this.dname = dname; } public Integer getEmpno() { return empno; } public void setEmpno(Integer empno) { this.empno = empno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public Date getHdate() { return hdate; } public void setHdate(Date hdate) { this.hdate = hdate; } public Float getSalary() { return salary; } public void setSalary(Float salary) { this.salary = salary; } public String getDname() { return dname; } public void setDname(String dname) { this.dname = dname; } }
示例程序:
import java.util.Calendar; import com.alibaba.fastjson.JSON; public class FastJsonSample1 { public static void main(String[] args) { Employee employee = new Employee(); employee.setEmpno(5566); employee.setEname("刘芳"); employee.setJob("运维工程师"); employee.setSalary(10000f); employee.setDname("工程部"); Calendar c = Calendar.getInstance(); // 月份是从0开始的,所以5代表六月; c.set(2020, 5, 16, 10, 38, 0); employee.setHdate(c.getTime()); // FastJson中提供了JSON对象,完成对象与JSON字符串的互相转换 String jsonString = JSON.toJSONString(employee); System.out.println(jsonString); } }
结果:
{"dname":"工程部","empno":5566,"ename":"刘芳","hdate":1592275080504,"job":"运维工程师","salary":10000.0}
……………………………………
一:附:@JSONField注解
发现,上面的hdate值是:1970年至当前设置时间的毫秒数,很难看懂;为了解决这个问题,需要用JSON注解来对日期格式进行格式化输出:@JSONField注解
此时再次运行的效果:
{"dname":"工程部","empno":5566,"ename":"刘芳","hdate":"2020-06-16 10:38:00 229","job":"运维工程师","salary":10000.0}
此时效果:
{"dname":"工程部","empno":5566,"ename":"刘芳","hdate":"2020-06-16","job":"运维工程师","salary":10000.0}
@JSONField注解还可以对输出的key进行描述:
如下在现实时,将不太容易明白什么意思的hdate换成了hiredate;
@JSONField注解还可以取消个别属性的JSON序列化:
如下,dname这个属性不重要,在转成JSON时不想要dname属性了:
二:将JSON字符串转换为对象(反序列化)
Employee emp = JSON.parseObject(jsonString, Employee.class):第一个参数为待转换的JSON字符串,第二个参数为想要转换的类;
package com.imooc.json; import java.util.Calendar; import com.alibaba.fastjson.JSON; public class FastJsonSample1 { public static void main(String[] args) { Employee employee = new Employee(); employee.setEmpno(5566); employee.setEname("刘芳"); employee.setJob("运维工程师"); employee.setSalary(10000f); employee.setDname("工程部"); Calendar c = Calendar.getInstance(); // 月份是从0开始的,所以5代表六月; c.set(2020, 5, 16, 10, 38, 0); employee.setHdate(c.getTime()); // FastJson中提供了JSON对象,完成对象与JSON字符串的互相转换 String jsonString = JSON.toJSONString(employee); System.out.println(jsonString); // 将字符串反序列化为对象 Employee emp = JSON.parseObject(jsonString, Employee.class); System.out.println(emp.getEname()); } }
-
Gson将Java对象转换成Json字符串
2021-03-16 17:08:49首先创建两个Bean如下:package ...import java.util.Date;import java.util.List;public class SendByUserIds {private List userIds;private String content;private int messageType;private Args args;pri...首先创建两个Bean如下:
package com.kxw.test.bean;
import java.util.Date;
import java.util.List;
public class SendByUserIds {
private List userIds;
private String content;
private int messageType;
private Args args;
private Date expiredTime;
private String pwd;
private String groupId;
private String appName;
private String title;
private String titleColor;
private String bgColor;
private String contentColor;
private String bgPic;
public List getUserIds() {
return userIds;
}
public void setUserIds(List userIds) {
this.userIds = userIds;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getMessageType() {
return messageType;
}
public void setMessageType(int messageType) {
this.messageType = messageType;
}
public Args getArgs() {
return args;
}
public void setArgs(Args args) {
this.args = args;
}
public Date getExpiredTime() {
return expiredTime;
}
public void setExpiredTime(Date expiredTime) {
this.expiredTime = expiredTime;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitleColor() {
return titleColor;
}
public void setTitleColor(String titleColor) {
this.titleColor = titleColor;
}
public String getBgColor() {
return bgColor;
}
public void setBgColor(String bgColor) {
this.bgColor = bgColor;
}
public String getContentColor() {
return contentColor;
}
public void setContentColor(String contentColor) {
this.contentColor = contentColor;
}
public String getBgPic() {
return bgPic;
}
public void setBgPic(String bgPic) {
this.bgPic = bgPic;
}
}
package com.kxw.test.bean;
public class Args {
private int type;
private String value;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
测试程序如下:
package com.kxw.test.kxwTest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.kxw.test.bean.Args;
import com.kxw.test.bean.SendByUserIds;
public class TestJson {
public static void main(String[] args) {
SendByUserIds sendByUserIds=new SendByUserIds();
List list=new ArrayList();
sendByUserIds.setUserIds(list);
Args args2=new Args();
sendByUserIds.setArgs(args2);
sendByUserIds.getUserIds().add("000676");
sendByUserIds.getUserIds().add("000643");
sendByUserIds.getUserIds().add("000653");
sendByUserIds.getUserIds().add("000876");
sendByUserIds.setAppName("Arsenal,Kaka',22,Kingson");
sendByUserIds.setContent("托雷斯");
sendByUserIds.setMessageType(2);
sendByUserIds.setTitle("切尔西");
sendByUserIds.setExpiredTime( new Date());
sendByUserIds.getArgs().setType(4);
sendByUserIds.getArgs().setValue("Messi");
//生成Gson对象,把对象及其属性对象转换为Json字符串,
Gson g = new GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.create();
String jsonResult = g.toJson(sendByUserIds);
System.out.println(jsonResult);
}
}
结果:
{"userIds":["000676","000643","000653","000876"],"content":"托雷斯","messageType":2,"args":{"type":4,"value":"Messi"},"expiredTime":"2014-04-17 14:39:03","appName":"Arsenal,Kaka\u0027,22,Kingson","title":"切尔西"}
附:
http://blog.csdn.net/king87130/article/details/8009923
//生成Gson对象,把对象及其属性对象转换为Json字符串,
//解决子属性对象的无限递归问题,只转换我们用标签暴露的对象类型
Gson g = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.serializeNulls()
.setDateFormat(DateFormat.LONG)
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.setPrettyPrinting()
.setVersion(1.0)
.create();
String jsonResult = g.toJson(sysUser.getPageResult());
System.out.println(jsonResult);
response.setContentType("application/json;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
out.print(jsonResult);
out.flush();
out.close();
-
将Date日期类型的字段转换成json字符串
2015-12-03 09:06:27但是,如果我们将数据转换成json格式的时候,我们也许会遇到Date日期型的数据转换成json格式后,并不是我们想要的格式。下面我们通过简单的demo 来说明这个问题。 我们按照一般json格式生成,会出现以下问题: 采用... -
JSON的String字符串与Java的List列表对象的相互转换
2020-10-22 12:02:38主要介绍了JSON的String字符串与Java的List列表对象的相互转换,如果在浏览器端JSON是list则转为string结构来处理,需要的朋友可以参考下 -
Java中Date类型字段转成JSON字符串会自动转换为时间戳
2020-10-21 12:35:55将该实体类对象使用FastJSON转成JSON字符串后,发现时间字段变成了“148364681324”这样的时间戳 二、解决办法 针对上述问题,FastJSON提供了解决方法 方法1:在对应的实体类的属性上方定义一个注解 @JSONField... -
json字符串转化为对象集合(包含Date类型字段处理)
2021-05-25 18:42:34json字符串转对象List package com.xxxxx.emis.base.util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import ... -
springboot全局日期格式转换:前端字符串转为Date,后端Date转为json字符串
2020-08-21 15:39:58Field error in object 'diskFileAO' on ... codes [typeMismatch.diskFileAO.regulationInputTime,typeMismatch.regulationInputTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.co -
Java对象 转 JSON 字符串
2021-07-29 18:25:00本案例所有代码均为原创,使用Java手写,没有借鉴...它可以支持null,字符串,数字、日期、集合等多种类型,包括以上类型的多层嵌套,都没有问题。 源码不多,如下: import java.lang.reflect.Field; import java.lang -
常见java对象转换为json字符串处理!!!
2021-02-12 11:24:001、JSON简介1. 概念: JavaScript Object NotationJavaScript对象表示法Person p = new Person();p.setName("张三");p.setAge(23);p.setGender("男");var p = {"name":"张三","age":23,"gender":"男"};* json现在... -
JSON-JSON字符串转换成JSON对象、JSON对象数组、java实体类以及保存到List列表中
2021-03-12 20:19:24处理JSON字符串时,一直出错,写个样例后发现原来是没有弄清楚数据的格式问题。实现的是 JSONString 转换成java对象 或是 list列表实例类 Newspackage lyx.entity;/*** @author lyx** 2015-8-10上午10:14:38***新闻... -
DATE类型的时间,转成JSON字符串,会自动变成时间戳。
2022-03-24 17:57:29方法1:在对应的实体类的属性上方定义一个...方法2: 在servlet中将数据转换成json对象时,使用 JSON.toJSON(date,SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteDateUseDateFormat) ... -
js object转化为json字符串 json字符串转为js对象
2019-02-19 16:51:21object转化为json字符串 var data = new Object(); var jsonData = JSON.stringify(data); json字符串转为js对象 var jsonObj = eval(jsonStr); -
【SpringMVC】JSON字符串
2021-07-06 14:07:26文章目录一、什么JSON二、在前端js对象与JSON的相互转换三、SpringMVC中解决JSON字符串乱码问题(固定代码)四、通过Jackson将java对象转换成json字符串1. 将普通对象转化JSON2. 将时间类(Date)转换成JSON3. 封装... -
对象转换JSON字符串工具类(包括时间格式处理)
2021-05-26 22:26:16/** * @ClassName: JsonUtils * @author: YanYue * @date: 2021/5/26 * @Description: */ public class JsonUtils { private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:... -
oracle把sql转换成JSON字符串
2022-03-20 12:13:20-- Purpose : JSON特殊字符替换 FUNCTION replace_json_char(p_char VARCHAR2) RETURN VARCHAR2 IS l_char VARCHAR2(20000); l_temp_char VARCHAR2(100); BEGIN FOR i IN 1 .. length(p_char) LOOP l_temp_... -
Object类型数据转化为json字符串工具类
2021-05-25 18:39:37Object类型数据转json字符串 package com.xxxxx.emis.base.util; import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.core.JsonProcessingException; import ... -
java对象转换为JSON字符串
2017-08-26 23:26:30JackSon将java对象转换为JSON字符串 JackSon可以将java对象转换为JSON字符串,步骤如下: 1.导入JackSon 的jar包 2.创建ObjectMapper对象 3.使用ObjectMapper对象的writeValueAsString()方法将java对象... -
Java对象与JSON字符串互相转换
2019-09-06 14:14:50一、Java对象转为JSON字符串 二、JSON字符串转为Java对象 JSON解析器,常见的解析器:Jsonlib,Gson,fastjson,jackson介绍:Jackson 一、Java对象转为JSON字符串 1、引入需要的Jackson所需要的jar包(三个)... -
Json字符串转日期
2020-10-19 14:48:09// 忽略json字符串中不识别的属性 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 忽略无法转换的对象 objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS...