json前后台交互(四)

fastjson是一个比较好的工具包,使用起来也很方便。

一、

1.类,json对象转成json字符串

[java]  view plain  copy
  1. JSONObject json = new JSONObject();  
  2. json.put("page",1);  
  3. json.put("pageSize",10);  
  4. json.toJSONString();  
还有Map集合在放进JSONObject,变成json字符串
[java]  view plain  copy
  1. Map<T,T> map = new HashMap<T,T>();  
  2. map.put("page",1);  
  3. map.put("pageSize",10);  
  4. json.putAll(map);  
  5. json.toJSONString();   

将一个类变成一个json类型的字符串

[java]  view plain  copy
  1. JSONObject.toJSONString(object);  
  2. JSON.toJSONString(object)  

二、

1.在json变成雷对象之前先学会得到一个jsonObject中的某个数据的值

    

[java]  view plain  copy
  1. JSONOnject obj = new JSONObject();  
  2. //如果我们需要判断json中是否包含这个键值对,  
  3. (1).boolean b = obj.containKey("key");  
  4. (2).String res = obj.getString("key");  
  5.     if (res != null) {  
  6.         System.out.println(res);  
  7.     }  
  8.  //如果想继续得到JSONObject  
  9. JSONObject obj1 =obj.getJSONObject(str2);  
  10. //如果想继续得到值为字符串键值对;  
  11. String jsonStr = obj.getString("");  
  12. //如果是得到Object,适合得到对应的值,下面没有数据  
  13. Onject obj2 = obj.get(str2);   
  14. //如果知道对应值得类型,还可以直接得到该类型的数据,基本类型必须是它的包装类,举例  
  15. int num = obj.getInteger("num");  
  16. String s2 = obj.getBoolean("name");  


2.json字符串变成一个类对象,要求字符串必须符合json格式

[java]  view plain  copy
  1. JSONObject json = JSONObject.parseObject(str)  

后面都是在json类型的字符串已经转出JSONObject的基础上。

[java]  view plain  copy
  1. Object o = JSON.toJavaObject(json,Object.class);  
  2. Object o = json.toJavaObject(Object.class);(二选一)  
[java]  view plain  copy
  1. 得到List集合的两种方法。  
  2. JSONArray jsonArr = json.getJSONArray("");(从JSONObject得到JSONArray对象)  
  3. List<T> list = jsonArr.toJavaList(T.class);  

如果本身是数组形式的字符串可以使用下面的方法

[java]  view plain  copy
  1. List<T.class> list = JSON.parseArray(str,T.class);  

JSON字符串和java对象的互转【json-lib】

在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML、JSON等,JSON作为一个轻量级的数据格式比xml效率要高,XML需要很多的标签,这无疑占据了网络流量,JSON在这方面则做的很好,下面先看下JSON的格式,

JSON可以有两种格式,一种是对象格式的,另一种是数组对象,

{"name":"JSON","address":"北京市西城区","age":25}//JSON的对象格式的字符串

 

[{"name":"JSON","address":"北京市西城区","age":25}]//数据对象格式


从上面的两种格式可以看出对象格式和数组对象格式唯一的不同则是在对象格式的基础上加上了[],再来看具体的结构,可以看出都是以键值对的形式出现的,中间以英文状态下的逗号(,)分隔。

在前端和后端进行数据传输的时候这种格式也是很受欢迎的,后端返回json格式的字符串,前台使用js中的JSON.parse()方法把JSON字符串解析为json对象,然后进行遍历,供前端使用。

下面进入正题,介绍在JAVA中JSON和java对象之间的互转。

要想实现JSON和java对象之间的互转,需要借助第三方jar包,这里使用json-lib这个jar包,下载地址为:https://sourceforge.net/projects/json-lib/,json-lib需要commons-beanutils-1.8.0.jar、commons-collections-3.2.1.jar、commons-lang-2.5.jar、commons-logging-1.1.1.jar、ezmorph-1.0.6.jar五个包的支持,可以自行从网上下载,这里不再贴出下载地址。

json-lib提供了几个类可以完成此功能,例,JSONObject、JSONArray。从类的名字上可以看出JSONObject转化的应该是对象格式的,而JSONArray转化的则应该是数组对象(即,带[]形式)的。

一、java普通对象和json字符串的互转

  java对象--》》字符串

java普通对象指的是java中的一个java bean,即一个实体类,如,

复制代码
package com.cn.study.day3;

public class Student {
    //姓名
    private String name;
    //年龄
    private String age;
    //住址
    private String address;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", address="
                + address + "]";
    }
    

}
复制代码


 

上面是我的一个普通的java实体类,看json-lib如何把它转化为字符串形式,

复制代码
public static void convertObject() {
        
        Student stu=new Student();
        stu.setName("JSON");
        stu.setAge("23");
        stu.setAddress("北京市西城区");

        //1、使用JSONObject
        JSONObject json = JSONObject.fromObject(stu);
        //2、使用JSONArray
        JSONArray array=JSONArray.fromObject(stu);
        
        String strJson=json.toString();
        String strArray=array.toString();
        
        System.out.println("strJson:"+strJson);
        System.out.println("strArray:"+strArray);
    }
复制代码


 

我定义了一个Student的实体类,然后分别使用了JSONObject和JSONArray两种方式转化为JSON字符串,下面看打印的结果,

strJson:{"address":"北京市西城区","age":"23","name":"JSON"}
strArray:[{"address":"北京市西城区","age":"23","name":"JSON"}]

从结果中可以看出两种方法都可以把java对象转化为JSON字符串,只是转化后的结构不同。

  JSON字符串--》》java对象

上面说明了如何把java对象转化为JSON字符串,下面看如何把JSON字符串格式转化为java对象,

首先需要定义两种不同格式的字符串,需要使用\对双引号进行转义,

复制代码
public static void jsonStrToJava(){
        //定义两种不同格式的字符串
        String objectStr="{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}";
        String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}]";
    
        //1、使用JSONObject
        JSONObject jsonObject=JSONObject.fromObject(objectStr);
        Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
        
        //2、使用JSONArray
        JSONArray jsonArray=JSONArray.fromObject(arrayStr);
        //获得jsonArray的第一个元素
        Object o=jsonArray.get(0);
        JSONObject jsonObject2=JSONObject.fromObject(o);
        Student stu2=(Student)JSONObject.toBean(jsonObject2, Student.class);
        System.out.println("stu:"+stu);
        System.out.println("stu2:"+stu2);
        
    }
复制代码

打印结果为:

stu:Student [name=JSON, age=24, address=北京市西城区]
stu2:Student [name=JSON, age=24, address=北京市西城区]

从上面的代码中可以看出,使用JSONObject可以轻松的把JSON格式的字符串转化为java对象,但是使用JSONArray就没那么容易了,因为它有“[]”符号,所以我们这里在获得了JSONArray的对象之后,取其第一个元素即我们需要的一个student的变形,然后使用JSONObject轻松获得。

二、list和json字符串的互转

list--》》json字符串

 

复制代码
public static void listToJSON(){
        Student stu=new Student();
        stu.setName("JSON");
        stu.setAge("23");
        stu.setAddress("北京市海淀区");
        List<Student> lists=new ArrayList<Student>();
        lists.add(stu);
        //1、使用JSONObject
        //JSONObject listObject=JSONObject.fromObject(lists);
        //2、使用JSONArray
        JSONArray listArray=JSONArray.fromObject(lists);
        
        //System.out.println("listObject:"+listObject.toString());
        System.out.println("listArray:"+listArray.toString());
        
    }
复制代码

我把使用JSONObject的方式给注掉了,我们先看注释之前的结果,

Exception in thread "main" net.sf.json.JSONException: 'object' is an array. Use JSONArray instead

告诉我说有一个异常,通过查看源码发现,在使用fromObject方法的时候会先进行参数类型的判断,这里就告诉我们,传入的参数是一个array类型,因为使用的ArrayList,再来看,注释之后的结果,

listArray:[{"address":"北京市海淀区","age":"23","name":"JSON"}]

这样结果是正常的。
json字符串--》》list

从上面的例子可以看出list的对象只能转化为数组对象的格式,那么我们看下面的字符串到list的转化,

复制代码
public static void jsonToList(){
        String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}]";
        //转化为list
                List<Student> list2=(List<Student>)JSONArray.toList(JSONArray.fromObject(arrayStr), Student.class);
                
                for (Student stu : list2) {
                    System.out.println(stu);
                }
                //转化为数组
                Student[] ss =(Student[])JSONArray.toArray(JSONArray.fromObject(arrayStr),Student.class);
                for (Student student : ss) {
                    System.out.println(student);
                }
        
        
    }
复制代码

打印结果,

Student [name=JSON, age=24, address=北京市西城区]
Student [name=JSON, age=24, address=北京市西城区]

由于字符串的格式为带有“[]”的格式,所以这里选择JSONArray这个对象,它有toArray、toList方法可供使用,前者转化为java中的数组,或者转化为java中的list,由于这里有实体类进行对应,所以在使用时指定了泛型的类型(Student.class),这样就可以得到转化后的对象。

三、map和json字符串的互转

map--》》json字符串

复制代码
public static void mapToJSON(){
        Student stu=new Student();
        stu.setName("JSON");
        stu.setAge("23");
        stu.setAddress("中国上海");
        Map<String,Student> map=new HashMap<String,Student>();
        map.put("first", stu);
        
        //1、JSONObject
        JSONObject mapObject=JSONObject.fromObject(map);
        System.out.println("mapObject"+mapObject.toString());
        
        //2、JSONArray
        JSONArray mapArray=JSONArray.fromObject(map);
        System.out.println("mapArray:"+mapArray.toString());
    }
复制代码

打印结果,

mapObject{"first":{"address":"中国上海","age":"23","name":"JSON"}}
mapArray:[{"first":{"address":"中国上海","age":"23","name":"JSON"}}]

上面打印了两种形式。

json字符串--》》map

JSON字符串不能直接转化为map对象,要想取得map中的键对应的值需要别的方式,

复制代码
public static void jsonToMap(){
        String strObject="{\"first\":{\"address\":\"中国上海\",\"age\":\"23\",\"name\":\"JSON\"}}";
        
        //JSONObject
        JSONObject jsonObject=JSONObject.fromObject(strObject);
        Map map=new HashMap();
        map.put("first", Student.class);

//使用了toBean方法,需要三个参数
MyBean my
=(MyBean)JSONObject.toBean(jsonObject, MyBean.class, map); System.out.println(my.getFirst()); }
复制代码

打印结果,

Student [name=JSON, age=23, address=中国上海]

下面是MyBean的代码,

复制代码
package com.cn.study.day4;

import java.util.Map;

import com.cn.study.day3.Student;

public class MyBean {
    
    private Student first;

    public Student getFirst() {
        return first;
    }

    public void setFirst(Student first) {
        this.first = first;
    }

    

}
复制代码

使用toBean()方法是传入了三个参数,第一个是JSONObject对象,第二个是MyBean.class,第三个是一个Map对象。通过MyBean可以知道此类中要有一个first的属性,且其类型为Student,要和map中的键和值类型对应,即,first对应键 first类型对应值的类型。

关于复杂的JSON串转化为java对象的内容,在下篇中会继续说明。


车道指示器
目的是反绿并且反绿没开  就把反红关了
红  绿  to  绿  绿
最新
绿 绿  to  绿 红   backgreen on
绿 红  to  红 红   justgreen of
红 红  to  红 绿   BACK_RED  of
红 绿  to  绿 绿   JUST_RED  on
left justgreen justred  backgreen
红 红  to 左 左    前: justgreen   justred   backgreen  backred
		   后: justgreen   一样
把其它点设置成  INDEX_TYPE_ON   都控制成绿的时候  出现正绿反红
把其它点设置成  INDEX_TYPE_OF   都控制成绿的时候  出现正红反绿
{LEFT: 0, BACK_GREEN: 0, JUST_RED: 0, JUST_GREEN: 1, BACK_RED: 1}
points index_type
cdzsq加左转状态,目的是替换hdzsq  合并成一个
BACK_GREEN 0  BACK_RED 1  JUST_GREEN 1   JUST_RED 0
图标 BACK_GREEN + JUST_GREEN    EQ11UWN img/mapIcon/CDZSQ-0-1.png
右洞LI-7-1   上左下右
BACK_RED 1     把left 设置成1
JUST_GREEN 1
从左边数 第一个是justgreen   第二个是backgreen
		 0是红  1是绿

{"customerCode":"null","proLineCode":"null","name":"左洞LI-3-2","pileNo":"K0+200","serialNumber":"null","categoryCode":"CDZSQ","categoryName":"车道指示器","brand":"null","model":"null","placeOfOrigin":"null","imageUrl":"","oemName":"null","productionDate":"null","supplierCode":"null","supplierName":"null","purchaseDate":"null","guaranteeBeginDate":"null","warrantyPeriod":"null","oemPerson":"null","supplierPerson":"null","customerPerson":"null","oemPersonName":"null","customerName":"null","customerPhone":"null","oemPersons":"null","customerPersons":"null","points":"null","oems":"null","suppliers":"null","customers":"null","qrUrl":"null","modelName":"null","agentName":"null","attrInfo":"null","equipmentCode":"null","equipmentName":"null","customTag":"null","attrName":"null","value":"null","sectionCode":"null","type":"null","sectionName":"实验室测试隧道","configs":"null","equipmentsAttr":"[EquipmentsAttr [id=null, equipmentCode=EQ9814B, customTag=车道, name=车道, value=left, status=null, createTime=null, categoryCode=null]]","indexType":"{BACK_GREEN=0.0, JUST_RED=0.0, JUST_GREEN=1.0, BACK_RED=1.0}","count":"null","equStartSum":"0","equSum":"0","equFaultSum":"0","equDisConnectSum":"0","map":"null","parentId":"0","grade":"null","locations":"null","queryKey":"null","direction":"null","supplierPersonName":"null","customerPersonName":"null","country":"null","province":"null","city":"null","location":"null","comment":"null","lineName":"null","currentState":"3","currentStates":"null","state":"null","children":"null","equipmensInfo":"null","company":"null"}

{"customerCode":"null","proLineCode":"null","name":"li横洞门","pileNo":"0","serialNumber":"null","categoryCode":"CDZSQ","categoryName":"车道指示器","brand":"null","model":"null","placeOfOrigin":"null","imageUrl":"","oemName":"null","productionDate":"null","supplierCode":"null","supplierName":"null","purchaseDate":"null","guaranteeBeginDate":"null","warrantyPeriod":"null","oemPerson":"null","supplierPerson":"null","customerPerson":"null","oemPersonName":"null","customerName":"null","customerPhone":"null","oemPersons":"null","customerPersons":"null","points":"null","oems":"null","suppliers":"null","customers":"null","qrUrl":"null","modelName":"null","agentName":"null","attrInfo":"null","equipmentCode":"null","equipmentName":"null","customTag":"null","attrName":"null","value":"null","sectionCode":"null","type":"null","sectionName":"实验室测试隧道","configs":"null","equipmentsAttr":"[EquipmentsAttr [id=null, equipmentCode=EQM27R7, customTag=车道, name=车道, value=left, status=null, createTime=null, categoryCode=null]]","indexType":"{LEFT=0.0, BACK_GREEN=0.0, JUST_RED=0.0, JUST_GREEN=1.0, BACK_RED=1.0}","count":"null","equStartSum":"0","equSum":"0","equFaultSum":"0","equDisConnectSum":"0","map":"null","parentId":"0","grade":"null","locations":"null","queryKey":"null","direction":"null","supplierPersonName":"null","customerPersonName":"null","country":"null","province":"null","city":"null","location":"null","comment":"null","lineName":"null","currentState":"3","currentStates":"null","state":"null","children":"null","equipmensInfo":"null","company":"null"} 

select * from point where xid = 'DP_462755'
xid=DP_468970  xid=DP_930080   xid=DP_468970    xid=DP_462755
JUST_RED				JUST_GREEN			JUST_RED				BACK_GREEN   说明 把左转改成其它的时候,左转并没有控制

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值