javajson聚合(java組合和聚合)

本文目錄一覽:

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

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2025-01-06 15:17
下一篇 2025-01-06 15:25

相關推薦

  • Java JsonPath 效率優化指南

    本篇文章將深入探討Java JsonPath的效率問題,並提供一些優化方案。 一、JsonPath 簡介 JsonPath是一個可用於從JSON數據中獲取信息的庫。它提供了一種DS…

    編程 2025-04-29
  • java client.getacsresponse 編譯報錯解決方法

    java client.getacsresponse 編譯報錯是Java編程過程中常見的錯誤,常見的原因是代碼的語法錯誤、類庫依賴問題和編譯環境的配置問題。下面將從多個方面進行分析…

    編程 2025-04-29
  • Java騰訊雲音視頻對接

    本文旨在從多個方面詳細闡述Java騰訊雲音視頻對接,提供完整的代碼示例。 一、騰訊雲音視頻介紹 騰訊雲音視頻服務(Cloud Tencent Real-Time Communica…

    編程 2025-04-29
  • Java Bean載入過程

    Java Bean載入過程涉及到類載入器、反射機制和Java虛擬機的執行過程。在本文中,將從這三個方面詳細闡述Java Bean載入的過程。 一、類載入器 類載入器是Java虛擬機…

    編程 2025-04-29
  • Java Milvus SearchParam withoutFields用法介紹

    本文將詳細介紹Java Milvus SearchParam withoutFields的相關知識和用法。 一、什麼是Java Milvus SearchParam without…

    編程 2025-04-29
  • Java 8中某一周的周一

    Java 8是Java語言中的一個版本,於2014年3月18日發布。本文將從多個方面對Java 8中某一周的周一進行詳細的闡述。 一、數組處理 Java 8新特性之一是Stream…

    編程 2025-04-29
  • Java判斷字元串是否存在多個

    本文將從以下幾個方面詳細闡述如何使用Java判斷一個字元串中是否存在多個指定字元: 一、字元串遍歷 字元串是Java編程中非常重要的一種數據類型。要判斷字元串中是否存在多個指定字元…

    編程 2025-04-29
  • VSCode為什麼無法運行Java

    解答:VSCode無法運行Java是因為默認情況下,VSCode並沒有集成Java運行環境,需要手動添加Java運行環境或安裝相關插件才能實現Java代碼的編寫、調試和運行。 一、…

    編程 2025-04-29
  • Java任務下發回滾系統的設計與實現

    本文將介紹一個Java任務下發回滾系統的設計與實現。該系統可以用於執行複雜的任務,包括可回滾的任務,及時恢復任務失敗前的狀態。系統使用Java語言進行開發,可以支持多種類型的任務。…

    編程 2025-04-29
  • Java 8 Group By 會影響排序嗎?

    是的,Java 8中的Group By會對排序產生影響。本文將從多個方面探討Group By對排序的影響。 一、Group By的概述 Group By是SQL中的一種常見操作,它…

    編程 2025-04-29

發表回復

登錄後才能評論