• Java Json


    一、org.json

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

     

    Java中json的构造和解析,下载

    JSONObject json=new JSONObject();
    json.put("Article_id", "66496");

    java数组转json数组,再转json字符串:

    /*
     题目: 将颜色数组 红色,绿色,蓝色 转成 JSON 字符串
     */
    String[] colors={"红色","蓝色","绿色"};
    
    // JSONArray 存入 colors 
    try{
        JSONArray jsonArray=new JSONArray(colors);
        System.out.println(jsonArray.toString());
    } catch (JSONException e){
        e.printStackTrace();
    }

     

    Java之Json和数组、字符串、对象之间的转换

    // 1、字符串和对象转换为Json
    JSONObject jsonStr = JSONObject.fromObject(String);
    
    // 2、数组转换为Json
    JSONArray.fromObject(Array[])
    
    // 3、Json转换成字符串,使用toString()方法即可
    
    //4、Json转换成对象
    JSONObject.toBean(json);

     

    如何将JSON数组转换为普通Java数组?

    ArrayList<String> list = new ArrayList<String>();     
    JSONArray jsonArray = (JSONArray)jsonObject; 
    if (jsonArray != null) { 
       int len = jsonArray.length();
       for (int i=0;i<len;i++){ 
        list.add(jsonArray.get(i).toString());
       } 
    } 

    或者

    // 如果还没有JSONArray对象,调用
    JSONArray jsonArray = new JSONArray(jsonArrayString);
    
    //然后简单地循环遍历,构建自己的数组。
    List<String> list = new ArrayList<String>();
    for (int i=0; i<jsonArray.length(); i++) {
        list.add( jsonArray.getString(i) );
    }

    JSON & GSON - 读取 JSON 文件

    读前需要了解

    首先我用到Apache Common IO 2.5包java-JSON包

    1、针对小JSON文件

    {
      "name": "ALemon",
      "age": 24.2,
      "car": null,
      "major":["敲代码","学习"],
      "Nativeplace": {
      "city": "广州",
      "country": "China"
      }
    }

    思路过程:

    1. 获取文件
    2. 获取文件内容
    3. 转换为 JSON 对象
    4. 读取 JSON 对象
    import org.apache.commons.io.FileUtils;
    import org.json.JSONException;
    import org.json.JSONObject;
    import java.io.File;
    import java.io.IOException;
     
    public class Demo {
     
        public static void main(String args[]) throws IOException {
     
            File file=new File("mejson");
            String content= FileUtils.readFileToString(file,"UTF-8");
            JSONObject jsonObject=new JSONObject(content);
            System.out.println("姓名是:"+jsonObject.getString("name"));
            System.out.println("年龄:"+jsonObject.getDouble("age"));
            System.out.println("学到的技能:"+jsonObject.getJSONArray("major"));
            System.out.println("国家:"+jsonObject.getJSONObject("Nativeplace").getString("country"));
     
        }
    }

    2、针对大JSON文件

    如果您的JSON很小,那么对象模型很好,因为您可以加载所有数据并作为普通Java对象工作。当文件非常大时,您可能不想加载它全部进入内存。

    因此流和对象模型之间混合使用模式个人觉得是最佳选择。

    Json文件由数组Person对象形成。每个人都有的id,name,married状态和名单sons和daughters:

    [
      {
        "id" : 0,
        "married" : true,
        "name" : "George Moore",
        "sons" : null,
        "daughters" : [
          {
            "age" : 25,
            "name" : "Elizabeth"
          },
          {
            "age" : 28,
            "name" : "Nancy"
          },
          {
            "age" : 9,
            "name" : "Sandra"
          }
        ]
      },
      ...
    ]

    Person 类

    public class Person {
        private int id;
        private String name;
        private boolean married;
        ...
     
        // Getter/Setter methods
        ...
     
        @Override
        public String toString() {
            return "Person{" + "id=" + id + ", name=" + name + ... + '}';
        }
    }

    我们在这里要做的是在流和对象模型之间使用混合模式。我们将以流模式读取文件,每次我们找到一个人物对象时,我们将使用对象模型装配,重复该过程,直到找到所需的对象。

    public static void readStream() {
        try {
            JsonReader reader = new JsonReader(new InputStreamReader(stream, "UTF-8"));
            Gson gson = new GsonBuilder().create();
     
            // Read file in stream mode
            reader.beginArray();
            while (reader.hasNext()) {
                // Read data into object model
                Person person = gson.fromJson(reader, Person.class);
                if (person.getId() == 0 ) {
                    System.out.println("Stream mode: " + person);
                    break;
                }
            }
            reader.close();
        } catch (UnsupportedEncodingException ex) {
            ...
        } catch (IOException ex) {
            ...
        }
    }

    Ps:JsonReader 需要引入 Gson包。

    使用这种方法,我们将所有对象一个接一个地加载到内存而不是整个文件。

    其中 stream 为目标文件stream对象。 Gson 的 API 使用可以自行查询。

    此外,如果想一次将json中的内容装配到Person数组中,可以通过以下方法实现。但此方法会消耗较多的内存

    public static void readDom() {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            Gson gson = new GsonBuilder().create();
            Person[] people = gson.fromJson(reader, Person[].class);
     
            System.out.println("Object mode: " + people[0]);
     
        } catch (FileNotFoundException ex) {
            ...
        } finally {
            ...
        }
    }

     

     

    二、com.google.gson

    import com.google.gson.Gson;
    import com.google.gson.JsonArray;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject)jsonParser.parse(content);

    Gson介绍

    Gson解析json文件

    $Java-json系列(一):用GSON解析Json格式数据

    1、针对小JSON文件

    1.  
      {
    2.  
      "name": "ALemon",
    3.  
      "age": 24.2,
    4.  
      "car": null,
    5.  
      "major":["敲代码","学习"],
    6.  
      "Nativeplace": {
    7.  
      "city": "广州",
    8.  
      "country": "China"
    9.  
      }
    10.  
      }

    思路过程:

    1. 获取文件
    2. 获取文件内容
    3. 转换为 JSON 对象
    4. 读取 JSON 对象
    1.  
      import org.apache.commons.io.FileUtils;
    2.  
      import org.json.JSONException;
    3.  
      import org.json.JSONObject;
    4.  
      import java.io.File;
    5.  
      import java.io.IOException;
    6.  
       
    7.  
      public class Demo {
    8.  
       
    9.  
      public static void main(String args[]) throws IOException {
    10.  
       
    11.  
      File file=new File("mejson");
    12.  
      String content= FileUtils.readFileToString(file,"UTF-8");
    13.  
      JSONObject jsonObject=new JSONObject(content);
    14.  
      System.out.println("姓名是:"+jsonObject.getString("name"));
    15.  
      System.out.println("年龄:"+jsonObject.getDouble("age"));
    16.  
      System.out.println("学到的技能:"+jsonObject.getJSONArray("major"));
    17.  
      System.out.println("国家:"+jsonObject.getJSONObject("Nativeplace").getString("country"));
    18.  
       
    19.  
      }
    20.  
      }
  • 相关阅读:
    Altium Designer下载和安装
    python中的filter()函数
    Python基础
    Linux系统中的操作命令
    Linux、Windows中的mysql数据库操作语句
    在运行Django项目时,出现127.0.0.1 拒绝了我们的连接请求
    Django的model类新增字段重新迁移时出错 django.db.utils.OperationalError: (1054, "Unknown column 'course.course_image' in 'field list'")
    使用DataGrip删除数据表
    Windows系统下安装Redis
    Python生成随机验证码需要导入ttf字体文件
  • 原文地址:https://www.cnblogs.com/tanrong/p/10911092.html
Copyright © 2020-2023  润新知