本文目錄一覽:
java中字符串怎麼轉json?
string類型如果要轉換成json的話,就需要寫成這樣的形式,如下:\x0d\x0aString jsonStr =”{‘id’:’11’,’parentId’:’root’,’refObj’:{‘existType’:’exist’,’deptType’:’emp’,’treeNodeType’:’dept’}}”;\x0d\x0a JSONObject jsonObj = new JSONObject(jsonStr);\x0d\x0a JSONObject refObj = new JSONObject(jsonObj.getString(“refObj”));\x0d\x0a String existType = refObj.getString(“existType”);\x0d\x0a System.out.println(existType);\x0d\x0ajar使用的是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();
}
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/279807.html