您的位置:首页 > Web前端 > JavaScript

maven项目对json字符串进行解析

2017-09-27 09:49 323 查看
<!-- org.json -->
<dependency>

    <groupId>org.json</groupId>

    <artifactId>json</artifactId>

    <version>20090211</version>
</dependency>

案例:

package com.yanshu.test;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

public class JsonUtil {
public static void main(String[] args) throws JSONException {
String jsonContent = "{'hello':world,'abc':'xyz'}";
JSONObject jsonObject = new JSONObject(jsonContent);
String str1 = jsonObject.getString("hello");
String str2 = jsonObject.getString("abc");
System.out.println(str1);
System.out.println(str2);

}

}

案例 

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

public class Test {

public static void main(String args[]) throws JSONException {

String jsonContent = "{'hello':world,'abc':'xyz'}";

JSONObject jsonObject = new JSONObject(jsonContent);

String str1 = jsonObject.getString("hello");

String str2 = jsonObject.getString("abc");

System.out.println(str1);

System.out.println(str2);

System.out.println("------------------");

jsonContent = "[{'hello':333,'abc':'false','xyz':{'a':1,'b':'ab'}},{'hello':555,'abc':'true','xyz':{'a':2,'b':'ba'}}]";

JSONArray jsonArray = new JSONArray(jsonContent);

for(int i=0;i<jsonArray.length();i++){

JSONObject jsonobject2=jsonArray.getJSONObject(i);

int value1=jsonobject2.getInt("hello");

boolean value2=jsonobject2.getBoolean("abc");

// String value3=jsonobject2.getString("xyz");

JSONObject jsonobject3=jsonobject2.getJSONObject("xyz");

int value4=jsonobject3.getInt("a");

String value5=jsonobject3.getString("b");

System.out.println(value1);

System.out.println(value2);

System.out.println(value4);

System.out.println(value5);

}

}

}

输出结果

world

xyz

------------------

333

false

1

ab

555

true

2

ba

我的文件资源有json的jar包
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json