Java json google_Java googlecode JSON 解析示例

这篇博客演示了如何在Java中使用json-simple库来解析JSON数据。首先,介绍了pom.xml配置中引入json-simple的依赖。接着,提供了一个JSON数据文件作为示例。在Java解析类中,通过FileReader读取JSON文件,使用JSONParser解析数据。然后从JSONObject获取字符串、长整型数据,遍历并打印JSONArray中的元素,以及解析嵌套的JSONObject。整个过程展示了Java处理JSON的基本步骤。

1.pom.xml配置

com.googlecode.json-simple

json-simple

1.1

2.准备JSON数据文件jsonTestFile.json

{

"id": 1,

"firstname": "Katerina",

"languages": [

{

"lang": "en",

"knowledge": "proficient"

},

{

"lang": "fr",

"knowledge": "advanced"

}

],

"job": {

"site": "www.javacodegeeks.com",

"name": "Java Code Geeks"

}

}

3.Java 解析类

package com.javacodegeeks.javabasics.jsonparsertest;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.util.Iterator;

import org.json.simple.JSONArray;

import org.json.simple.JSONObject;

import org.json.simple.parser.JSONParser;

import org.json.simple.parser.ParseException;

public class JsonParseTest {

private static final String filePath = "C:\\Users\\katerina\\Desktop\\jsonTestFile.json";

public static void main(String[] args) {

try {

// read the json file

FileReader reader = new FileReader(filePath);

JSONParser jsonParser = new JSONParser();

JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

// get a String from the JSON object

String firstName = (String) jsonObject.get("firstname");

System.out.println("The first name is: " + firstName);

// get a number from the JSON object

long id = (long) jsonObject.get("id");

System.out.println("The id is: " + id);

// get an array from the JSON object

JSONArray lang= (JSONArray) jsonObject.get("languages");

// take the elements of the json array

for(int i=0; i

System.out.println("The " + i + " element of the array: "+lang.get(i));

}

Iterator i = lang.iterator();

// take each value from the json array separately

while (i.hasNext()) {

JSONObject innerObj = (JSONObject) i.next();

System.out.println("language "+ innerObj.get("lang") +

" with level " + innerObj.get("knowledge"));

}

// handle a structure into the json object

JSONObject structure = (JSONObject) jsonObject.get("job");

System.out.println("Into job structure, name: " + structure.get("name"));

} catch (FileNotFoundException ex) {

ex.printStackTrace();

} catch (IOException ex) {

ex.printStackTrace();

} catch (ParseException ex) {

ex.printStackTrace();

} catch (NullPointerException ex) {

ex.printStackTrace();

}

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值