首页 > 编程知识 正文

java转json串的几种方式,java json字符串转对象的方法

时间:2023-12-29 13:16:42 阅读:329986 作者:BAYM

本文目录一览:

java中字符串怎么转json?

string类型如果要转换成json的话,就需要写成这样的形式,如下:x0dx0aString jsonStr ="{'id':'11','parentId':'root','refObj':{'existType':'exist','deptType':'emp','treeNodeType':'dept'}}";x0dx0a JSONObject jsonObj = new JSONObject(jsonStr);x0dx0a JSONObject refObj = new JSONObject(jsonObj.getString("refObj"));x0dx0a String existType = refObj.getString("existType");x0dx0a System.out.println(existType);x0dx0ajar使用的是org.json.jar

如何构建json串,并将map转为jsonObject对象的三种方式(scala)

众所周知,kafka中存储的数据是经过BASE64加密后的jsonObject,因此从kafka中读取的数据经过base64解码,得到的是json串,利用JSONObect的方法可以对json串进行解析,拿到对应的数据。那么要如何将scala对象或者java对象转换为JsonObject对象或JSONObject对象呢?(注意:JsonObject对象和JSONObject对象不同,调用的API也不一样)

三种转换方式依赖的包源码都是用JAVA编写,所以构建Map对象时完全使用java对象,不会发生错误。构建过程如下:

三种将java对象转换为jsonObject对象的开源包有:

1、google提供的Genson是一个完全的Java和JSON转换的类库,提供了全面的数据绑定、流操作等。基于Apache 2.0协议发布。转换结果为

JsonObject对象。

使用需要先导入Jar包:import com.google.gson.{Gson, JsonParser}

引入依赖:这里选用版本为:2.2.4,具体版本可以根据业务需求选择。

dependency

groupIdcom.google.code.gson/groupId

artifactIdgson/artifactId

version2.2.4/version

/dependency

2、Fastjson 是一个 Java 库,可以将 Java 对象转换为 JSON 格式,当然它也可以将 JSON 字符串转换为 Java 对象。

导入jar包:import com.alibaba.fastjson.JSON

引入依赖:

dependency

groupIdcom.alibaba/groupId

artifactIdfastjson/artifactId

version1.2.8/version

/dependency

3、net.sf.json-lib方式

导入jar包:import net.sf.json.JSONObject

引入依赖:

dependency

groupIdnet.sf.json-lib/groupId

artifactIdjson-lib-ext-spring/artifactId

version1.0.2/version

/dependency

java中json格式转换有哪些方法

用自带的解析工具

package cn.edu.bzu.json;

 

import java.io.FileNotFoundException;

import java.io.FileReader;

 

import com.google.gson.JsonArray;

import com.google.gson.JsonIOException;

import com.google.gson.JsonObject;

import com.google.gson.JsonParser;

import com.google.gson.JsonSyntaxException;

 

public class Read {

    public static void main(String args[]){

        JsonParser parse =new JsonParser();  //创建json解析器

        try {

            JsonObject json=(JsonObject) parse.parse(new FileReader("weather.json"));  //创建jsonObject对象

            System.out.println("resultcode:"+json.get("resultcode").getAsInt());  //将json数据转为为int型的数据

            System.out.println("reason:"+json.get("reason").getAsString());     //将json数据转为为String型的数据

             

            JsonObject result=json.get("result").getAsJsonObject();

            JsonObject today=result.get("today").getAsJsonObject();

            System.out.println("temperature:"+today.get("temperature").getAsString());

            System.out.println("weather:"+today.get("weather").getAsString());

             

        } catch (JsonIOException e) {

            e.printStackTrace();

        } catch (JsonSyntaxException e) {

            e.printStackTrace();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        }

    }

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。