本文目錄一覽:
- 1、Java解析json數據
- 2、java中json怎麼運用?
- 3、JAVA,當某個json數據中一個欄位與另一個json數據中的欄位值相同時,對兩個json進行合併且相加,
- 4、求java合併json數據的代碼
- 5、java json取集合某個元素
Java解析json數據
一、 JSON (JavaScript Object Notation)一種簡單的數據格式,比xml更輕巧。
Json建構於兩種結構:
1、「名稱/值」對的集合(A collection of name/value pairs)。不同的語言中,它被理解為對象(object),紀錄(record),結構(struct),字典(dictionary),哈希表(hash table),有鍵列表(keyed list),或者關聯數組 (associative array)。 如:
{
「name」:」jackson」,
「age」:100
}
2、值的有序列表(An ordered list of values)。在大部分語言中,它被理解為數組(array)如:
{
「students」:
[
{「name」:」jackson」,「age」:100},
{「name」:」michael」,」age」:51}
]
}
二、java解析JSON步驟
A、伺服器端將數據轉換成json字元串
首先、伺服器端項目要導入json的jar包和json所依賴的jar包至builtPath路徑下(這些可以到JSON-lib官網下載:)
然後將數據轉為json字元串,核心函數是:
public static String createJsonString(String key, Object value)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
return jsonObject.toString();
}
B、客戶端將json字元串轉換為相應的javaBean
1、客戶端獲取json字元串(因為android項目中已經集成了json的jar包所以這裡無需導入)
public class HttpUtil
{
public static String getJsonContent(String urlStr)
{
try
{// 獲取HttpURLConnection連接對象
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
// 設置連接屬性
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setRequestMethod(“GET”);
// 獲取相應碼
int respCode = httpConn.getResponseCode();
if (respCode == 200)
{
return ConvertStream2Json(httpConn.getInputStream());
}
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return “”;
}
private static String ConvertStream2Json(InputStream inputStream)
{
String jsonStr = “”;
// ByteArrayOutputStream相當於內存輸出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
// 將輸入流轉移到內存輸出流中
try
{
while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
{
out.write(buffer, 0, len);
}
// 將內存流轉換為字元串
jsonStr = new String(out.toByteArray());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonStr;
}
}
2、獲取javaBean
public static Person getPerson(String jsonStr)
{
Person person = new Person();
try
{// 將json字元串轉換為json對象
JSONObject jsonObj = new JSONObject(jsonStr);
// 得到指定json key對象的value對象
JSONObject personObj = jsonObj.getJSONObject(“person”);
// 獲取之對象的所有屬性
person.setId(personObj.getInt(“id”));
person.setName(personObj.getString(“name”));
person.setAddress(personObj.getString(“address”));
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return person;
}
public static ListPerson getPersons(String jsonStr)
{
ListPerson list = new ArrayListPerson();
JSONObject jsonObj;
try
{// 將json字元串轉換為json對象
jsonObj = new JSONObject(jsonStr);
// 得到指定json key對象的value對象
JSONArray personList = jsonObj.getJSONArray(“persons”);
// 遍歷jsonArray
for (int i = 0; i personList.length(); i++)
{
// 獲取每一個json對象
JSONObject jsonItem = personList.getJSONObject(i);
// 獲取每一個json對象的值
Person person = new Person();
person.setId(jsonItem.getInt(“id”));
person.setName(jsonItem.getString(“name”));
person.setAddress(jsonItem.getString(“address”));
list.add(person);
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
java中json怎麼運用?
json一般都是配合ajax一起使用的 我做做過的小例子 粘給你 你可以研究一下
js部分
//獲取卡的金額
function get_money(){
var str=document.getElementById(“pk_card_type”).value;
//alert(str);
var url = ‘/member_h.do’;
var pars = ‘method=getMoney’;
pars+=’pk_card_type=’+str;
var ajax = new Ajax.Request(
url,
{method:’post’,parameters:pars,onComplete:show_money}
);
}
//回調函數 寫入卡的金額
function show_money(dataResponse)
{
var data = eval(‘(‘ + dataResponse.responseText + ‘)’);
var price=0;
price=data.price;
var collection_fees=0;
collection_fees=data.collection_fees;
document.getElementById(“recharge”).value=price;
document.getElementById(“collection_fees”).value=collection_fees;
}
action部分
public ActionForward getMoney(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
response.setContentType(“text/html; charset=utf-8”);
try {
IElementaryFileService ggsv = new ElementaryFileService();
String pk_card_type = request.getParameter(“pk_card_type”);
Card_TypeVO ctvo=new Card_TypeVO();
ctvo=ggsv.queryByPK(Card_TypeVO.class, pk_card_type);
PrintWriter out = response.getWriter();
// 這裡的數據拼裝一般是從資料庫查詢來的
JSONObject jsonObject = new JSONObject();
if(ctvo!=null){
jsonObject.put(“price”, ctvo.getCard_money());
jsonObject.put(“collection_fees”, ctvo.getCash());
}else{
jsonObject.put(“price”, 0);
jsonObject.put(“collection_fees”, 0);
}
out.print(jsonObject.toString());
out.flush();
out.close();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
JAVA,當某個json數據中一個欄位與另一個json數據中的欄位值相同時,對兩個json進行合併且相加,
要判斷json數據的欄位與其他數據是否相同,那麼肯定是要先解析json數據。解析json數據的方式很多,Gson、FastJson都是很簡便實用的工具。這裡以Gson為例。
import java.lang.reflect.Type;
import java.util.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Divination {
public static void main(String[] args) {
String jsonStr = “[{\”depid\”:\”5\”,\”score\”:\”10\”},{\”depid\”:\”4\”,\”score\”:\”40\”},{\”depid\”:\”4\”,\”score\”:\”30\”},{\”depid\”:\”5\”,\”score\”:\”30\”}]”;
System.out.println(“原始的json字元串:” + jsonStr);
// 解析
Gson gson = new Gson();
Type type = new TypeTokenArrayListJsonData() {
}.getType();
ArrayListJsonData list = gson.fromJson(jsonStr, type);
// 合併
ListJsonData ordered = new ArrayList();
MapInteger, JsonData map = new HashMap();
for (JsonData jsonData : list) {
JsonData data = map.get(jsonData.getDepid());
if (data != null) { // depid相同的合併score欄位
data.setScore(data.getScore() + jsonData.getScore());
} else {
map.put(jsonData.getDepid(), jsonData);
ordered.add(jsonData);
}
}
// 還原為json字元串
System.out.println(“合併後json字元串:” + gson.toJson(map.values()));
System.out.println(“合併後json字元串(按原來的順序):” + gson.toJson(ordered));
}
}
class JsonData {
private int depid;
private int score;
public int getDepid() {
return depid;
}
public void setDepid(int depid) {
this.depid = depid;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
以上代碼中ListJsonData ordered = new ArrayList();是為了按原json數組的順序輸出合併後的結果,如果對順序無要求可以刪除相關代碼。
運行結果:
求java合併json數據的代碼
我想了一下,但是得有一個前提,就是第一個json數組的size必須和第二個json數組的size相同,並且一一對應,否則將造成數組溢出。
如果是基於上面這個前提,那麼實現的方法就簡單了。
操作json對象,其實標準的方法是將實體類轉換成json後再操作,我這裡的話為了便捷直接使用谷歌的Gson來創建JsonObject了,其他的json依賴還有阿里巴巴的FastJson等等,看你平時用什麼習慣。
引入Gson依賴:
dependency
groupIdcom.google.code.gson/groupId
artifactIdgson/artifactId
version2.8.0/version
/dependency
實現代碼:
public class Main {
public static void main(String[] args) {
JsonArray jsonArray1 = new JsonArray();
JsonObject json11 = new JsonObject();
json11.addProperty(“數據1”, “0000”);
json11.addProperty(“數據2”, “1111”);
JsonObject json12 = new JsonObject();
json12.addProperty(“數據1”, “0000”);
json12.addProperty(“數據2”, “1111”);
JsonObject json13 = new JsonObject();
json13.addProperty(“數據1”, “0000”);
json13.addProperty(“數據2”, “1111”);
jsonArray1.add(json11);
jsonArray1.add(json12);
jsonArray1.add(json13);
System.out.println(jsonArray1);
JsonArray jsonArray2 = new JsonArray();
JsonObject json21 = new JsonObject();
json21.addProperty(“數據3”, “6666”);
JsonObject json22 = new JsonObject();
json22.addProperty(“數據3”, “6666”);
JsonObject json23 = new JsonObject();
json23.addProperty(“數據3”, “6666”);
jsonArray2.add(json21);
jsonArray2.add(json22);
jsonArray2.add(json23);
System.out.println(jsonArray2);
//遍歷json數組,按位取出對象
for (int i = 0; i jsonArray1.size(); i++) {
JsonObject json1 = jsonArray1.get(i).getAsJsonObject();
JsonObject json3 = jsonArray2.get(i).getAsJsonObject();
//遍曆數據3內容,通過Entry獲取數據3的key和value,併合併到數據1中
for (Map.EntryString, JsonElement item : json3.entrySet()) {
json1.addProperty(item.getKey(), item.getValue().getAsString());
}
}
System.out.println(jsonArray1);
}
}
整體思路為:遍歷兩個json數組,按位進行合併操作。合併時,遍曆數據3的jsonObject,獲取其key和value,並將其合併到數據1中即可。
運行結果:
java json取集合某個元素
首先你的這個json串就有問題,修改下才能解析,解析方法如下
JSONObject log=jsonObject.getJSONObject(“第一級Object”);
JSONArray jsonArray = log.getJSONArray(“Object中的array”);
JSONObject pages = jsonArray.getJSONObject(0); //從jsonArray中解析第一個Object
JSONObject pageTimings=pages.getJSONObject(“繼續解析object”);
String onContentLoad=pageTimings.getString(“onContentLoad”); //得到想要的值
把{}大括弧擴起來的看成是object,如果有名字就根據名字來解析,如果沒名字就根據序號來解析,上面的代碼兩種情況均有涉及,請注意參考與更改變數名。[]擴起來的看成數組,用getArray解析,同樣可以用名字或序號解析
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/313013.html