简体   繁体   English

从Java中读取JSON文件的最简单方法?

[英]Simplest way to read from a JSON file in Java?

I'm relatively new to using JSON and all I really need to do read in a few key value pairs from a JSON file on the file system. 我是使用JSON的新手,我真正需要做的就是从文件系统上的JSON文件中读取几个键值对。 What I figured I would do is read in the file as a string and then parse it that way but it seems kind of redundant that way. 我以为我会做的事情是将文件作为字符串读取,然后以这种方式解析,但这种方式似乎有点多余。

Here's what my file will be like: 这是我的文件的样子:

 {
 "username" : "myname"
 "domain" : "mydomain"
 }

So essentially I need some help making an easy and efficient block of code to read in the key/value pairs. 因此,从本质上讲,我需要一些帮助来制作一个简单有效的代码块以读取键/值对。 I've been trying to use GSON for the most part and haven't had much luck with examples I've found. 我大部分时间一直在尝试使用GSON,但对我发现的示例并不太幸运。

Thanks everyone 感谢大家

One other alternative is JSON.org , in which creating a JSON object from a JSON string requires only one line: 另一种选择是JSON.org ,其中从JSON字符串创建JSON对象只需要一行:

JSONObject jsonObject = new JSONObject(someJSONString);

When you need to access its value, use the functions that the JSONObject provides. 当您需要访问其值时,请使用JSONObject提供的功能。 For example, 例如,

String userName = jsonObject.getString("username");
String domainName = jsonObject.getString("mydomain");

在这里看看如何使用gson将其转换为多汁的数据的示例: 将JSON转换为Java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM