導航:首頁 > 源碼編譯 > 編譯原理json解析

編譯原理json解析

發布時間:2023-05-30 14:47:16

❶ json的解析

varobj={
"info":{
"success":true,
"code":null,
"error":null
},
"data":[{
"id":1,
"name":"測試用戶",
"loginName":"test",
"password":"test",
"mobile1":null,
"mobile2":null,
"telephone":null,
"email":null,
"gender":null,
"address":null,
"removed":0
},{
"id":21,
"name":"研發團隊測試",
"loginName":"testTWW",
"password":"testTWW",
"mobile1":null,
埋型"mobile2":null,
"telephone":null,
"email":null,
判哪"gender":null,
"address":null,
"removed":0
}]
};

vardata=obj["掘液碼data"];

❷ JSON中數組該如何解析呢c++中使用jsoncpp

JSON是一個輕量級的數據定義格式,比起XML易學易用,而擴展功能不比XML差多少,用之進行數據交換是一個很好的選擇
JSON的全稱為:javaScript Object Notation ,顧名思義,JSON是用於標記javascript對象的,詳情參考http://www.json.org/。
本文選擇第三方庫JsonCpp來解析json,JsonCpp是比較出名的c++解析庫,在json官網也是首推的。
JsonCpp簡介
JsonCpp主要包含三種類型的class:Value Reader Writer。
jsoncpp中所有對象、類名都在namespace json中,包含json.h即可。
注意: Json::Value只能處理ANSI類型的字元串,如果C++程序使用Unicode編碼的,最好加一個Adapt類來適配。
下載和編譯
本文運行環境是: Redhat 5.5 + g++version 4.6.1 + GNU Make 3.81 + jsoncpp-0.5.0
下載地址是:http://sourceforge.net/projects/jsoncpp/
解壓之後得到jsoncpp-src-0.5.0文件夾,我們只需要jsoncpp的頭文件和cpp文件,其中jsonscpp的頭文件位於jsoncpp-src-0.5.0includejson,jsoncpp的cpp文件位於jsoncpp-src-0.5.0srclib_json。
這里我列出我們的工作目錄:
jsoncpp/ //工作目錄
|-- include //頭文件根目錄
| |-- json //json頭文件,對應jsoncpp-src-0.5.0includejson
|-- src //cpp源碼文件根目錄
|-- json //jsoncpp源碼文件,對應jsoncpp-src-0.5.0srclib_json
|-- main.cpp //我們的主函數,調用jsoncpp的示例代碼
|-- makefile //makefile,不用我們多說了吧,不懂請看我博客的makefile最佳實踐
反序列化Json對象
假設有一個json對象如下:

{ "name": "json″, "array": [ { "cpp": "jsoncpp" }, { "java": "jsoninjava" }, { "php": "support" } ] }

我們要實現這個json的反序列號代碼如下:
voidreadJson() { usingnamespacestd; std::stringstrValue = "{\"name\":\"json\",\"array\":[{\"cpp\":\"jsoncpp\"},{\"java\":\"jsoninjava\"},{\"php\":\"support\"}]}"; Json::Reader reader; Json::Value value; if(reader.parse(strValue, value)) { std::stringout= value["name"].asString(); std::cout <<out<<std::endl; constJson::Value arrayObj = value["array"]; for(unsigned inti = 0;i <arrayObj.size(); i++) { if(!arrayObj[i].isMember("cpp")) continue; out= arrayObj[i]["cpp"].asString(); std::cout <<out; if(i != (arrayObj.size() - 1)) std::cout <<std::endl; } } }

序列化Json對象
voidwriteJson() { usingnamespacestd; Json::Value root; Json::Value arrayObj; Json::Value item; item["cpp"] = "jsoncpp"; item["java"] = "jsoninjava"; item["php"] = "support"; arrayObj.append(item); root["name"] = "json"; root["array"] = arrayObj; root.toStyledString(); std::stringout= root.toStyledString(); std::cout <<out<<std::endl; }

python3.0怎麼用json從文件解析

1、說明:
python3通過json模塊load函數來解析文件。
2、代碼示例:
首先編寫一個json文件j.txt,內容如下:
{"errno":1,"errmsg":"操作成功!","data":[]}
python代碼如下:

importjson
withopen('j.txt','r')asfr:
o=json.load(fr)
print(o['errno'])
print(o['errmsg'])
print(len(o['data']))

輸出如下:
1
操作成功!
0
3、函數說明:
load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
反序列化fp(一個.read()包含 - 支持類文件對象一個JSON文件),以一個Python對象。
object_hook是將與被調用的可選功能任何對象文本解碼(一個``dict``)的結果。返回值object_hook將用來代替dict。此功能可用於實現自定義解碼器(例如JSON-RPC級提示)。
object_pairs_hook是將與被調用的可選功能任何對象的結果與對的有序列表字面解碼。該的返回值object_pairs_hook將用來代替dict。
此功能可用於實現依賴於定製解碼器命令該鍵和值對被解碼(例如,collections.OrderedDict會記得插入的順序)。如果object_hook也定義了object_pairs_hook優先。
要使用自定義JSONDecoder子類,與cls指定它kwarg;否則JSONDecoder使用。
4、其它說明:
也可以使用json.loads函數來直接處理字元串,方法如下:
o=json.loads('{"errno":0,"errmsg":"操作成功!","data":[]}')

❹ 如何解析返回的json格式數據

json數據格式解析我自己分為兩種;
一種是普通的,一種是帶有數組形式的;
普通形式的:
伺服器端返回的json數據格式如下:

復制代碼代碼如下:

{"userbean":{"Uid":"100196","Showname":"\u75af\u72c2\u7684\u7334\u5b50","Avtar":null,"State":1}}

分析代碼如下:

復制代碼代碼如下:

// TODO 狀態處理 500 200
int res = 0;
res = httpClient.execute(httpPost).getStatusLine().getStatusCode();
if (res == 200) {
/*
* 當返回碼為200時,做處理
* 得到伺服器端返回json數據,並做處理
* */
HttpResponse httpResponse = httpClient.execute(httpPost);
StringBuilder builder = new StringBuilder();
BufferedReader bufferedReader2 = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent()));
String str2 = "";
for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2
.readLine()) {
builder.append(s);
}
Log.i("cat", ">>>>>>" + builder.toString());

JSONObject jsonObject = new JSONObject(builder.toString())
.getJSONObject("userbean");
String Uid;
String Showname;
String Avtar;
String State;
Uid = jsonObject.getString("Uid");
Showname = jsonObject.getString("Showname");
Avtar = jsonObject.getString("Avtar");
State = jsonObject.getString("State");

帶數組形式的:
伺服器端返回的數據格式為:

復制代碼代碼如下:

{"calendar":
{"calendarlist":
[
{"calendar_id"態做:"1705","title":"(\u4eb2\u5b50)ddssd","category_name"橘拿:"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288927800","endshowtime":"1288931400","allDay":false},
{"calendar_id":"1706","title":"(\u65c5\u884c)","category_name":"帆伍衡\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288933200","endshowtime":"1288936800","allDay":false}
]
}
}

分析代碼如下:

復制代碼代碼如下:

// TODO 狀態處理 500 200
int res = 0;
res = httpClient.execute(httpPost).getStatusLine().getStatusCode();
if (res == 200) {
/*
* 當返回碼為200時,做處理
* 得到伺服器端返回json數據,並做處理
* */
HttpResponse httpResponse = httpClient.execute(httpPost);
StringBuilder builder = new StringBuilder();
BufferedReader bufferedReader2 = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent()));
String str2 = "";
for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2
.readLine()) {
builder.append(s);
}
Log.i("cat", ">>>>>>" + builder.toString());
/**
* 這里需要分析伺服器回傳的json格式數據,
*/
JSONObject jsonObject = new JSONObject(builder.toString())
.getJSONObject("calendar");
JSONArray jsonArray = jsonObject.getJSONArray("calendarlist");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i);
CalendarInfo calendarInfo = new CalendarInfo();
calendarInfo.setCalendar_id(jsonObject2.getString("calendar_id"));
calendarInfo.setTitle(jsonObject2.getString("title"));
calendarInfo.setCategory_name(jsonObject2.getString("category_name"));
calendarInfo.setShowtime(jsonObject2.getString("showtime"));
calendarInfo.setEndtime(jsonObject2.getString("endshowtime"));
calendarInfo.setAllDay(jsonObject2.getBoolean("allDay"));
calendarInfos.add(calendarInfo);
}

總結,普通形式的只需用JSONObject ,帶數組形式的需要使用JSONArray 將其變成一個list。

❺ 關於解析各種復雜json

def dict_generator(indict, pre=None):

    pre = pre[:] if pre else []

    if isinstance(indict, dict):

        for key, value in indict.items():

            if isinstance(value, dict):

                if len(value) == 0:

           雀斗轎         yield pre + [key, '{}']

                else:

                    for d in dict_generator(value, pre + [key]):

                        yield d

            elif isinstance(value, list):

                if len(value) == 0:

                    yield pre + [key, '[]']

                else:

                    for v in value:

                        for d in dict_generator(v, pre + [key]):

                            yield d

            elif isinstance(value, tuple):

                if len(value) == 0:

                    yield pre + [key, '()']

                else:

                    for v in value:

                        for d in dict_generator(v, pre + [key]):

                            yield d

            else:

                yield pre + [key, value]

    else:

        yield indict

def print_keyvalue_by_key(input_json, key):

    key_value = ""

    if isinstance(input_json, dict):

        for json_result in input_json.values():

            if key in input_json.keys():

                key_value = input_json.get(key)

            else:

                print_keyvalue_by_key(json_result, key)

    elif isinstance(input_json, list):

        for json_array in input_json:

            print_keyvalue_by_key(json_array, key)

    if key_value != "":

        for value in key_value:

            if "contents" == key:

                s = value[:-1].lstrip("[")

                json_loads = json.loads(s)

                json_mps = json.mps(json_loads)

                return json_mps

            else:

                list_add.append(value)

 頃肆       return list_add

def get_all_field(data,key,params_key):

"""遞歸解析json

    :param data: json數據

    :return: key的值和params_key的值""銷兄"

        if isinstance(data,dict):

            for k, vin data.items():

                if key == kand params_key in data:

                    yield v,data[params_key]

                elif k !=params_key:

                    for a, bin get_all_field(v,key,params_key):

                        yield a, b    

        elif isinstance(data,list):

            for v in data:

                for a, b in get_all_field(v,key,params_key):

                    yield a, b

if __name__ =='__main__':

        for a,b in  get_all_field(json, filed,param):

                print(a,b)    

❻ 怎麼用程序解析一個json文件

一、要解決這個問題首先要知道json格式是什麼?

JSON格式:
比如學生有學號,姓名,性別等。
用json表示則為:
{"studno"羨舉賀:"11111","studname":"wwww","studsex":"男"}(各個欄位都是字元型)

這代表一個學生的信息。

如果多個呢?

[{"studno":"122222","studname":"wwww","studsex":"男"},
{"studno":"11111","studname":"xxxx","studsex":"男"},
{"studno":"33333","studname":"ssss","studsex":"男"}]

這就是json格式。

二、那如何操作json格式的文件呢?

這個更簡單了,說白了就是直接讀寫文件,再把讀出來的文件內容格式化成json就可以了。

三、具體操作。

1.我有一個實體類,如下:

public class ElectSet {
public String xueqi;
public String xuenian;
public String startTime;
public String endTime;
public int menshu;
public String isReadDB;
//{"xueqi":,"xuenian":,"startTime":,"endTime":,"renshu":,"isReadDB":}
public String getXueqi() {
return xueqi;
}
public void setXueqi(String xueqi) {
this.xueqi = xueqi;
}
public String getXuenian() {
return xuenian;
}
public void setXuenian(String xuenian) {
this.xuenian = xuenian;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public int getMenshu() {
return menshu;
}
public void setMenshu(int menshu) {
this.menshu = menshu;
}
public String getIsReadDB() {
return isReadDB;
}
public void setIsReadDB(String isReadDB) {
this.isReadDB = isReadDB;
}

}

2.有一個json格式的文件,存的就是他的信息兄派,如下

Sets.json:
{"xuenian":"2007-2008","xueqi":"1","startTime":"2009-07-19 08:30","endTime":"2009-07-22 18:00","menshu":"10","isReadDB":"Y"}

3.具體操作.
/*
* 取出文件內容,填充對象
*/
public ElectSet findElectSet(String path){
ElectSet electset=new ElectSet();
String sets=ReadFile(path);//獲得json文件的內容
JSONObject jo=JSONObject.fromObject(sets);//格式化成json對象
//System.out.println("------------"答枯 jo);
//String name = jo.getString("xuenian");
//System.out.println(name);
electset.setXueqi(jo.getString("xueqi"));
electset.setXuenian(jo.getString("xuenian"));
electset.setStartTime(jo.getString("startTime"));
electset.setEndTime(jo.getString("endTime"));
electset.setMenshu(jo.getInt("menshu"));
electset.setIsReadDB(jo.getString("isReadDB"));
return electset;
}
//設置屬性,並保存
public boolean setElect(String path,String sets){
try {
writeFile(path,sets);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
//讀文件,返回字元串
public String ReadFile(String path){
File file = new File(path);
BufferedReader reader = null;
String laststr = "";
try {
//System.out.println("以行為單位讀取文件內容,一次讀一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
//一次讀入一行,直到讀入null為文件結束
while ((tempString = reader.readLine()) != null) {
//顯示行號
System.out.println("line " line ": " tempString);
laststr = laststr tempString;
line ;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return laststr;
}
//把json格式的字元串寫到文件
public void writeFile(String filePath, String sets) throws IOException {
FileWriter fw = new FileWriter(filePath);
PrintWriter out = new PrintWriter(fw);
out.write(sets);
out.println();
fw.close();
out.close();
}

4.調用,使用(在網站的controller里調用的)

//取出json對象
public void GetElectSettings(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ElectSet electset=new ElectSet();
String absPath = request.getRealPath("\");
String filePath = absPath "public\sets\electSets.json";
electset=businessService.findElectSets(filePath);//這里是調用,大家自己改改,我調用的業務層 的。
JSONArray jsonItems = new JSONArray();
jsonItems.add(electset);
JSONObject jo=new JSONObject();
jo.put("data", jsonItems);
System.out.println(jo);
request.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.print(jo);
}

//修改json文件
public void ChangeElectSet(HttpServletRequest request,
HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/json;charset=utf-8");
log.info("reach ChangeElectSet");
String json = (String) request.getParameter("json").trim();
log.info("Change ElectSet");
log.info(json);
ElectSet sets = new ElectSet();
JSONObject jsonObject = JSONObject.fromObject(json);
sets = (ElectSet) JSONObject.toBean(jsonObject, ElectSet.class);
if(sets.getIsReadDB()=="false"){
sets.setIsReadDB("否");
}
else{
sets.setIsReadDB("是");
}
String changes="{"xuenian":"";//因為json的屬性要用引號,所以要用"轉義一下
changes =sets.getXuenian() "","xueqi":"" sets.getXueqi() "","startTime":"" sets.getStartTime() "","endTime":"" sets.getEndTime() "","menshu":"" sets.getMenshu() "","isReadDB":"" sets.getIsReadDB() ""}";
System.out.println(changes);
String absPath = request.getRealPath("\");
String filePath = absPath "public\sets\electSets.json";
轉載

❼ 如何解析這個的JSON 文件

1、添加dll
2、string的串傳入序鏈碰大列吵鏈化成json就行了
前端會自動解析json的

C# code?

#region

//MemcachedClient mc = new MemcachedClient();
string test = "{a, b}";

#endregion
protected void Page_Load(object sender, EventArgs e)
{
// log4net.ILog log = log4net.LogManager.GetLogger("log");
ReturnJsonString(test);
}

public string ReturnJsonString(string test)
{
if (test.Length <= 0) return "[]"棚豎;
return JsonConvert.SerializeObject(test).ToString();
}

❽ Android 中解析 JSON

JSON( JavaScript Object Notation ) 是一種輕量級的數據交換格式。易於閱讀和編寫,同時也易於機器解析和生成。

JSON 建構於兩種結構:

JSON 具有以下這些格式:

參考: Android 中 解析 JSON

Android 提供類四種不同的類來操作 JSON 數據。這些類是 JSONArray、JSONObject、JSONStringer 和 JSONTokenizer

為了解析 JSON 對象,須先創建一個 JSONObject 類的對象,需要傳入需解析的字元串 JSONObject root = new JSONObject(candyJson); 然後根據 JSONObject 對象提供方法以及數據類型解析對應 json 數據。下表展示一些 JSONObiect 提供的方法

示例:

❾ 如何java解析json數組

工具/原料

閱讀全文

與編譯原理json解析相關的資料

熱點內容
伺服器怎麼用不會斷電 瀏覽:298
主從伺服器有什麼用 瀏覽:213
jstlpdf 瀏覽:14
安卓原神在哪個app下載 瀏覽:808
單片機編程技術什麼意思 瀏覽:104
e點課堂源碼 瀏覽:45
免費打擊墊app哪個好 瀏覽:532
程序員必裝的6款軟體 瀏覽:750
基於單片機的遙控器設計 瀏覽:521
安卓如何取消圓圖標 瀏覽:11
收件伺服器怎麼樣 瀏覽:48
建築設計規范pdf 瀏覽:98
如何合並兩個pdf 瀏覽:174
刷機包必須要解壓的單詞 瀏覽:483
android課表實現 瀏覽:864
頭條app在哪裡能看見有什麼活動 瀏覽:511
冰櫃壓縮機電容80歐 瀏覽:609
安卓各個版本圖標什麼樣 瀏覽:152
無錫哪裡有製作手機app 瀏覽:538
php字元串轉json數組 瀏覽:6