Java json google_Java googlecode JSON 解析示例

本文演示了如何在Java中使用json-simple库解析JSON数据。通过读取jsonTestFile.json文件,获取并打印JSON对象的各个字段,包括字符串、数字、数组及嵌套对象中的信息。
摘要由CSDN通过智能技术生成

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();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值