JSON、JSONObject和JSONArray简介

目录

定义

FastJson中JsonObject的常用方法

构建Json对象

JavaBean转Json

Json转JavaBean


定义

JSON:就是一种轻量级的数据交换格式,被广泛应用于WEB应用程序开发。JSON的简洁和清晰的层次结构,易于阅读和编写;同时也易于机器解析和生成,有效的提升网络传输效率;支持多种语言,很多流行的语言都对JSON格式有着很友好的支持。

JSON对象:就是多个属性被{}括起来的。

JSON数组:就是包含了多个JSON对象的一个集合,数组是以数组括号[]括起来的。JSON数组并不一定是要相同的JSON对象的集合,也可以是不同的对象。

JSON、JSON对象、JSON数组的区别

JSON是一种数据结构,类型xml;

JSON对象则是对JSON的具体体现;JSON数组则是将多个JSON对象进行存储的一个集合。

FastJson中JsonObject的常用方法

JSONObject

JSONObject是根据JSON形式在java中存在的对象映射。各大JSON类库的JSONObject内部实现也是不太一样。以fastjson为例,就是实现了Map接口。其使用方式和HashMap并无太大区别。

{
  "area": "武汉",
  "name": "张三",
  "age": 25
}

JSONArray

JSONArray就是存放JSONObject的容器。以fastjson为例,就是实现了List接口,默认创建为ArrayList。

[{
  “area”: “武汉”,
  “name”: “张三”,
  “age”: 25
  },
  {
    “area”: “深圳”,
  “name”: “李四”,
  “age”: 22
  }]

通俗来讲 JSONObject 是对象的json形式 JSONArry 是对象集合的JSON形式。

先来看下它有哪些常用方法,以及有什么作用:

1.put(String key, Object value)方法,在JSONObject对象中设置键值对在,在进行设值得时候,key是唯一的,如果用相同的key不断设值得时候,保留后面的值。

2.Object get(String key) :根据key值获取JSONObject对象中对应的value值,获取到的值是Object类型,需要手动转化为需要的数据类型

3.int size():获取JSONObject对象中键值对的数量

4.boolean isEmpty():判断该JSONObject对象是否为空

5.containsKey(Object key):判断是否有需要的key值

6.boolean containsValue(Object value):判断是否有需要的value值

7.JSONObject getJSONObject(String key):如果JSONObjct对象中的value是一个JSONObject对象,即根据key获取对应的JSONObject对象;

8.JSONArray getJSONArray(String key) :如果JSONObject对象中的value是一个JSONObject数组,既根据key获取对应的JSONObject数组;

9.Object remove(Object key):根据key清除某一个键值对。

由于JSONObject是一个map,它还具有map特有的两个方法

10.Set<String> keySet() :获取JSONObject中的key,并将其放入Set集合中

11.Set<Map.Entry<String, Object>> entrySet():在循环遍历时使用,取得是键和值的映射关系,Entry就是Map接口中的内部接口

与String字符串转换:

12.toJSONString() /toString():将JSONObject对象转换为json的字符串

常用的方法主要为以上这些,下面列出使用这些方法的example:

public static void main(String[] args) {
        //新建JSONObject对象
        JSONObject object1 = new JSONObject();
        
        //1.在JSONObject对象中放入键值对
        object1.put("1","a");
        object1.put("2","b");
        object1.put("3","c");
        
        //2.根据key获取value
        String name = (String) object1.get("1");
        System.out.println(1);
        
        //3.获取JSONObject中的键值对个数
        int size = object1.size();
        System.out.println(size);
        
        //4.判断是否为空
        boolean result = object1.isEmpty();
        System.out.println(result);
        
        //5.是否包含对应的key值,包含返回true,不包含返回false
        boolean isContainsKeyResult = object1.containsKey("1");
        System.out.println(isContainsKeyResult);
        
        //6.是否包含对应的value值,包含返回true,不包含返回false
        boolean isContainsValueResult = object1.containsValue("a");
        System.out.println(isContainsValueResult);
        
        //7.JSONObjct对象中的value是一个JSONObject对象,即根据key获取对应的JSONObject对象;
        JSONObject object2 = new JSONObject();
        //将jsonobject对象作为value进行设置
        object2.put("student1", object1);
        JSONObject student =object2.getJSONObject("student1");
        System.out.println(student);
        
        //8.如果JSONObject对象中的value是一个JSONObject数组,既根据key获取对应的JSONObject数组;
        JSONObject objectArray = new JSONObject();
        //创建JSONArray数组
        JSONArray jsonArray = new JSONArray();
        //在JSONArray数组设值:jsonArray.add(int index, Object value);
        jsonArray.add(0, "this is a jsonArray value");
        jsonArray.add(1, "another jsonArray value");
        objectArray.put("testArray", jsonArray);
        //获取JSONObject对象中的JSONArray数组
        JSONArray jsonArray2 = objectArray.getJSONArray("testArray");
        System.out.println(jsonArray2);
        
        //9.remove.根据key移除JSONObject对象中的某个键值对
        object1.remove("name");
        System.out.println(object1);
        
        //10.取得JSONObject对象中key的集合
        Set<String> keySet= object1.keySet();
        for (String key : keySet) {
            System.out.print("   "+key);
        }
        System.out.println();
        
        //11.取得JSONObject对象中的键和值的映射关系
        Set<Map.Entry<String, Object>> entrySet = object1.entrySet();
        for (Entry<String, Object> entry : entrySet) {
            System.out.println(entry);
        }
        
        //12.转换为json字符串
        String str1 = object1.toJSONString();
        System.out.println(str1);
        String str2 =object1.toString();
        System.out.println(str2);
    }

构建Json对象

// Json对象中添加的是键值对,JSONArray中添加的是Json对象
JSONObject jsonObject = new JSONObject();  
jsonObject.put("1","a");
jsonObject.put("2","b");
jsonObject.put("3","c");
JSONArray JsonArray = new JSONArray();  
  
jsonObject.put("key", "value");//JSONObject对象中添加键值对  
JsonArray.add(jsonObject);//将JSONObject对象添加到Json数组中  

JavaBean转Json

User user = new User();
user.setName("张三");
user.setAget("32");
user.setSex(null);

现需要转换,我采用的方法是:

JSONObject jsonObjectData = (JSONObject) JSONObject.toJSON(user);

转出来的结果是:

jsonObjectData只有两个key(name与age),sex丢失了。

看了下jdk api文档,发现这是序列化造成的,JSONObject.toJSON默认是不序列化null值对应的key的,改成如下就对了。

JSONObject jsonObjectData = (JSONObject) JSONObject.toJSON(user,SerializeConfig.getGlobalInstance());

复杂的JsonBean转Json

直接把里面的属性取出来 复制给 新对象,然后将新对象序列化 JSONObject.toJSONString()

Json转JavaBean

 String str="{"password":"admin","gender":true,"name":"张三","telephone":"123456","id":1,"account":"admin"}";
   // 前面是JSON字符串 后面是java对象类型
   User user=JSONObject.parseObject(str,User.class);
   System.out.println("account: "+user.getAccount()+"---"+"paasword: "+user.getPassword());
String listStr = "[{\"id\":1,\"name\":\"vivi\"},{\"id\":2,\"name\":\"jojo\"}]";
    // (1)转Json List
    JSONArray jsonArray = JSONArray.parseArray(listStr);
    System.out.println(jsonArray);
    // (2)转具体的List<实体类>
    List<Demo> listDemo = jsonArray.toJavaList(Demo.class);
    for (Demo demo : listDemo){
        System.out.println(demo.toString());
    }
}
// 简单写法
List<Demo> listDemo = JSONArray.parseArray(listStr,Demo.class)

遍历JsonObject

public static void main(String[] args) throws Exception {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("1","a");
    jsonObject.put("2","b");
    jsonObject.put("3","c");

    for (String a : jsonObject.keySet()){
        System.out.println("key:"+a+";Value:"+jsonObject.get(a));
    }
}

输出:

key:1;Value:a

key:2;Value:b

key:3;Value:c

  • 3
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
包含以下java源文件: com.google.gson.DefaultDateTypeAdapter.class com.google.gson.ExclusionStrategy.class com.google.gson.FieldAttributes.class com.google.gson.FieldNamingPolicy.class com.google.gson.FieldNamingStrategy.class com.google.gson.Gson.class com.google.gson.GsonBuilder.class com.google.gson.InstanceCreator.class com.google.gson.JsonArray.class com.google.gson.JsonDeserializationContext.class com.google.gson.JsonDeserializer.class com.google.gson.JsonElement.class com.google.gson.JsonIOException.class com.google.gson.JsonNull.class com.google.gson.JsonObject.class com.google.gson.JsonParseException.class com.google.gson.JsonParser.class com.google.gson.JsonPrimitive.class com.google.gson.JsonSerializationContext.class com.google.gson.JsonSerializer.class com.google.gson.JsonStreamParser.class com.google.gson.JsonSyntaxException.class com.google.gson.LongSerializationPolicy.class com.google.gson.TreeTypeAdapter.class com.google.gson.TypeAdapter.class com.google.gson.TypeAdapterFactory.class com.google.gson.annotations.Expose.class com.google.gson.annotations.SerializedName.class com.google.gson.annotations.Since.class com.google.gson.annotations.Until.class com.google.gson.internal.ConstructorConstructor.class com.google.gson.internal.Excluder.class com.google.gson.internal.JsonReaderInternalAccess.class com.google.gson.internal.LazilyParsedNumber.class com.google.gson.internal.LinkedTreeMap.class com.google.gson.internal.ObjectConstructor.class com.google.gson.internal.Primitives.class com.google.gson.internal.Streams.class com.google.gson.internal.UnsafeAllocator.class com.google.gson.internal.bind.ArrayTypeAdapter.class com.google.gson.internal.bind.CollectionTypeAdapterFactory.class com.google.gson.internal.bind.DateTypeAdapter.class com.google.gson.internal.bind.JsonTreeReader.class com.google.gson.internal.bind.JsonTreeWriter.class com.google.gson.internal.bind.MapTypeAdapterFactory.class com.google.gson.internal.bind.ObjectTypeAdapter.class com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.class com.google.gson.internal.bind.SqlDateTypeAdapter.class com.google.gson.internal.bind.TimeTypeAdapter.class com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.class com.google.gson.internal.bind.TypeAdapters.class com.google.gson.reflect.TypeToken.class com.google.gson.stream.JsonReader.class com.google.gson.stream.JsonScope.class com.google.gson.stream.JsonToken.class com.google.gson.stream.JsonWriter.class com.google.gson.stream.MalformedJsonException.class

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值