读取和写入 JSON 文件 Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10966776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading and Writing JSON file Java
提问by rexbelia
I'm trying to read a JSON file into a data structure so that I can count a bunch of elements.
我正在尝试将 JSON 文件读入数据结构,以便我可以计算一堆元素。
The JSON file is of the format [{String, String, [], String } ... ]
. Now in this array of objects, I need to find the relationship of the first string field (let's say association) to the array field (names of the members). I need to figure out how many associations each of these members belong to.
JSON 文件的格式为[{String, String, [], String } ... ]
. 现在在这个对象数组中,我需要找到第一个字符串字段(假设关联)与数组字段(成员名称)的关系。我需要弄清楚这些成员中的每一个都属于多少个协会。
I'm currently using json-simple and this is how I've done it.
我目前正在使用 json-simple,这就是我的做法。
Object obj = parser.parse(new FileReader("c://Users/James McNulty/Documents/School/CMPT 470/Ex 4/exer4-courses.json"));
JSONArray jsonArray = (JSONArray) obj;
ArrayList<JSONObject> courseInfo = new ArrayList<JSONObject>();
Iterator<JSONObject> jsonIterator = jsonArray.iterator();
while (jsonIterator.hasNext()) {
courseInfo.add(jsonIterator.next());
count++;
//System.out.println(jsonIterator.next());
}
//System.out.println(count);
String course = "";
String student = "";
ArrayList<JSONArray> studentsPerCourse = new ArrayList<JSONArray>();
for (int i=0; i<count; i++) {
course = (String) courseInfo.get(i).get("course");
studentsPerCourse.add((JSONArray) courseInfo.get(i).get("students"));
System.out.println(course);
System.out.println(studentsPerCourse.get(i));
}
ArrayList<String> students = new ArrayList<String>();
for (int i=0; i<count; i++) {
for (int j=0; j< (studentsPerCourse.get(i).size()); j++) {
students.add((String) studentsPerCourse.get(i).get(j));
//System.out.println(studentsPerCourse.get(i).get(j));
}
//System.out.println(student);
}
JSONObject object = new JSONObject();
Map<String, Integer> studentCourses = new HashMap<String, Integer>();
Set<String> unique = new HashSet<String>(students);
for (String key : unique) {
studentCourses.put(key, Collections.frequency(students, key));
object.put(key, Collections.frequency(students, key));
//System.out.println(key + ": " + Collections.frequency(students, key));
}
FileWriter file = new FileWriter("c://Users/James McNulty/Documents/School/CMPT 470/Ex 4/output.json");
file.write(object.toJSONString());
file.flush();
file.close();
System.out.print(object);
Wondering if there is a simpler way in simple-json itself or if there are other libraries that better.
想知道 simple-json 本身是否有更简单的方法,或者是否有其他更好的库。
回答by Denys Séguret
Google gsonis very simple to use both for encoding and decoding.
Google gson用于编码和解码都非常简单。
The simplest way is to fill an object by simply letting the engine fill the fields using reflection to map them to the content of the file as described here: the deserialization is just the call to gson.fromJson(json, MyClass.class);
once you created your class.
最简单的方法是通过简单地让引擎使用反射填充字段以将它们映射到文件的内容来填充对象,如下所述:反序列化只是在gson.fromJson(json, MyClass.class);
创建类后调用。
回答by JakeWilson801
Seems like you're trying to do what they call Collections in Java. First I would look at your json model. Build a class that holds the properties you listed above. Then the code will look like this.
似乎您正在尝试在 Java 中执行他们所谓的集合。首先我会看看你的 json 模型。构建一个包含上面列出的属性的类。然后代码看起来像这样。
public void parseJson(){
// Read your data into memory via String builder or however you choose.
List<modelthatyoubuilt> myList = new ArrayList<modelthatyoubuilt>();
JSONArray myAwarry = new JSONArray(dataString);
for(int i = 0; i < myAwarry.size(); i++){
JSONObject j = myAwarry.get(i);
modelthatyoubuilt temp = new modelthatyoubuilt();
temp.setProperty(j.getString("propertyname");
//do that for the rest of the properties
myList.add(temp);
}
public int countObjects(ArrayList<modelthatyoubuilt> s){
return s.size();
}
Hope this helps.
希望这可以帮助。
回答by Kamlesh
public class AccessData {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String USER_AGENT = "Mozilla/5.0";
try {
String url = "https://webapp2017sql.azurewebsites.net/api/customer";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes("{\"Id\":1,\"Name\":\"Kamlesh\"} ");
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}catch (Exception ex) {
System.out.print(ex.getMessage());
//handle exception here
} finally {
//Deprecated
//httpClient.getConnectionManager().shutdown();
}
}
}
回答by RANA DINESH
If you are new to JSON then first try below example to create json file and write data in it;
如果您不熟悉 JSON,请先尝试下面的示例来创建 json 文件并在其中写入数据;
public class JSONWrite
{
public static void main(String[] args)
{
// JSONObject class creates a json object
JSONObject obj= new JSONObject();
// provides a put function to insert the details into json object
obj.put("name", "Dinesh");
obj.put("phone", "0123456789");
obj.put("Address", "BAngalore");
// This is a JSON Array List where we Creates an array
JSONArray Arr = new JSONArray();
// Add the values in newly created empty array
Arr.add("JSON Array List 1");
Arr.add("JSON Array List 2");
Arr.add("JSON Array List 3");
// adding the array with elements to our JSON Object
obj.put("Remark", Arr);
try{
// File Writer creates a file in write mode at the given location
FileWriter file = new FileWriter(IAutoconstant.JSONLPATH);
// Here we convert the obj data to string and put/write it inside the json file
file.write(obj.toJSONString());
file.flush();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Please find below codes to read the data from above json file
请找到以下代码以从上面的 json 文件中读取数据
// use JsonParser to convert JSON string into Json Object
// 使用 JsonParser 将 JSON 字符串转换为 Json 对象
JSONParser parser= new JSONParser();
// parsing the JSON string inside the file that we created earlier
// 解析我们之前创建的文件中的 JSON 字符串
Object obj=parser.parse(new FileReader(IAutoconstant.JSONLPATH));
// Json string has been converted into JSONObject
// Json 字符串已转换为 JSONObject
JSONObject jsonObject =(JSONObject)obj;
// Display values from JSON OBject by using Keys
// 使用键显示来自 JSON 对象的值
String value1 = (String) jsonObject.get("name");
System.out.println("value1 is "+value1);
// converting the JSONObject into JSONArray as remark was an array.
// 将 JSONObject 转换为 JSONArray,因为备注是一个数组。
JSONArray arrayobject=(JSONArray) jsonObject.get("Remark");
// Iterator is used to access the each element in the list
// 迭代器用于访问列表中的每个元素
Iterator<String> it = arrayobject.iterator();
// loop will continue as long as there are elements in the array.
// 只要数组中有元素,循环就会继续。
while(it.hasNext())
{
System.out.println(it.next());
}
}
Hope it help to understand the concept of json read.write
希望对理解json read.write的概念有所帮助