瑞星 发表于 2024-7-23 23:16:40

Java 实现字符串String转换成json

<dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.83</version> <!-- 替换为最新版本 -->
</dependency>
Java 实现字符串String转换json(JSON格式)
package com.cn;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {
      try {
            // 读取 JSON 文件内容为字符串
            String jsonString = new String(Files.readAllBytes(Paths.get("example.json")));

            // 将 JSON 字符串解析为 JSONObject 对象
            JSONObject jsonObject = JSON.parseObject(jsonString);

            // 从 JSONObject 中获取数据
            String name = jsonObject.getString("name");
            int age = jsonObject.getInteger("age");

            // 打印数据
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
      } catch (IOException e) {
            e.printStackTrace();
      }
    }
}


 Java 实现字符串String转换List(JSONArray格式)

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSON;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

String filePath="example.json";
try {
        String content=new String(Files.readAllBytes(Paths.get(filePath)));
        List<JSONObject> res = new ArrayList<>();
        JSONArray json = JSONArray.parseArray(content);
        for(int i = 0; i < json.size(); i++) {
                res.add(json.getJSONObject(i));
        }
        System.out.println(res);
} catch (IOException e) {
        e.printStackTrace();
}






免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Java 实现字符串String转换成json