gpt4 book ai didi

java - 下面是尝试通过java程序从文本文件读取的json数据。面临解析错误

转载 作者:行者123 更新时间:2023-12-01 16:36:09 24 4
gpt4 key购买 nike

Json data from text file

{"projectkey":"proj1"} 
{"projectkey":"proj2"}
{"projectkey":"proj3"}

java code to read the json objects from above file

//package crunchify.com.tutorials;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.io.FileReader;
import java.util.Iterator;

/**
* @author Crunchify.com
* How to Read JSON Object From File in Java?
*/

public class DemoJson {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("W:\\FileDemo\\jsoninput.txt"));

A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface.

JSONObject jsonObject = (JSONObject) obj;

A JSON array. JSONObject supports java.util.List interface.

String projectkey = (String)jsonObject.get("projectkey");

// An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework.
// Iterators differ from enumerations in two ways:
// 1. Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
// 2. Method names have been improved.
Iterator<String> keys = (Iterator<String>) jsonObject.keySet();
while (keys.hasNext()) {
String key= keys.next();
if (jsonObject.get(key) instanceof JSONObject) {
System.out.println(jsonObject);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

最佳答案

您的 JSON 不正确,应该是

[
{
"projectkey":"proj1"
},
{
"projectkey":"proj2"
},
{
"projectkey":"proj3"
}
]

将上述 JSON 存储到字符串中(从文件中读取)

public static void main(String[] args) throws IOException {
String json = "[\r\n" +
" {\r\n" +
" \"projectkey\":\"proj1\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"projectkey\":\"proj2\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"projectkey\":\"proj3\"\r\n" +
" }\r\n" +
"]";
JSONArray array = new JSONArray(json);
for(int i=0; i<array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
Iterator<String> iterator = jsonObject.keys();
while(iterator.hasNext()) {
String key = iterator.next();
System.out.println("Key :: "+key+" value :: "+jsonObject.getString(key));
}
}
}

输出

Key :: projectkey  value :: proj1
Key :: projectkey value :: proj2
Key :: projectkey value :: proj3

关于java - 下面是尝试通过java程序从文本文件读取的json数据。面临解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61942844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com