如何在Java中解析JSON
我有以下JSON文本。如何解析它以获得如何在Java中解析JSON,java,json,parsing,Java,Json,Parsing,我有以下JSON文本。如何解析它以获得pageName、pagePic、post\u id等值 { “页面信息”:{ “页面名称”:“abc”, “pagePic”:http://example.com/content.jpg" }, “员额”:[ { “post_id”:“123456789012_123456789012”, “演员id”:“1234567890”, “发布者的照片”:http://example.com/photo.jpg", “发布者姓名”:“简·多伊”, “消息”:“听
pageName
、pagePic
、post\u id
等值
{
“页面信息”:{
“页面名称”:“abc”,
“pagePic”:http://example.com/content.jpg"
},
“员额”:[
{
“post_id”:“123456789012_123456789012”,
“演员id”:“1234567890”,
“发布者的照片”:http://example.com/photo.jpg",
“发布者姓名”:“简·多伊”,
“消息”:“听起来很酷。迫不及待地想看它!”,
“LikeCount”:“2”,
“评论”:[…],
“邮局时间”:“1234567890”
}
]
}
非常简单、灵活、快速且可定制。试试看
特点:
- 符合JSON规范(RFC4627)
- 高性能JSON解析器
- 支持灵活/可配置的解析方法
- 任何JSON层次结构的键/值对的可配置验证
- 易于使用#占地面积非常小
- 引发开发人员友好且易于跟踪的异常
- 可插拔自定义验证支持-可以在遇到时通过配置自定义验证程序来验证密钥/值
- 验证和非验证解析器支持
- 支持两种类型的配置(JSON/XML)以使用快速JSON验证解析器
- 需要JDK1.5
- 不依赖外部库
- 支持通过对象序列化生成JSON
- 在解析过程中支持集合类型选择
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(contentString);
String product = (String) jsonObject.get("productId");
我认为最好的做法应该是通过仍在进行中的官方文件。图书馆很容易使用 只要记住(在强制转换或使用诸如
getJSONObject
和getJSONArray
之类的方法时)在JSON表示法中
表示一个数组,所以库将把它解析为[…]
JSONArray
表示一个对象,所以库将把它解析为{…}
JSONObject
import org.json.*;
String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......
}
import org.json.*;
字符串jsonString=//在此处指定JSON字符串
JSONObject obj=新的JSONObject(jsonString);
String pageName=obj.getJSONObject(“pageInfo”).getString(“pageName”);
JSONArray arr=obj.getJSONArray(“posts”);//请注意“posts”:[…]`
对于(int i=0;i
您可以从以下内容中找到更多示例:
可下载的罐子:这让我惊讶于它是多么的简单。您只需将保存JSON的
字符串
传递给默认org.JSON包中JSONObject的构造函数即可
JSONArray rootOfPage = new JSONArray(JSONString);
完成了。放下话筒。
这也适用于JSONObjects
。之后,您可以使用对象上的get()
方法查看对象的层次结构
如果希望从JSON创建Java对象,反之亦然,请使用GSON或JACKSON第三方JAR等
//from object to JSON
Gson gson = new Gson();
gson.toJson(yourObject);
// from JSON to object
yourObject o = gson.fromJson(JSONString,yourObject.class);
但是,如果你只想解析一个JSON字符串并获取一些值(或者从头创建一个JSON字符串通过网络发送),只需使用JaveeeJAR,它包含JsonReader、JsonArray、JsonObject等。你可能需要下载该规范的实现,比如javax.JSON。通过这两个JAR,我能够解析json并使用这些值
这些API实际上遵循XML的DOM/SAX解析模型
Response response = request.get(); // REST call
JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
JsonArray jsonArray = jsonReader.readArray();
ListIterator l = jsonArray.listIterator();
while ( l.hasNext() ) {
JsonObject j = (JsonObject)l.next();
JsonObject ciAttr = j.getJsonObject("ciAttributes");
请这样做:
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(contentString);
String product = (String) jsonObject.get("productId");
{
“页面信息”:{
“页面名称”:“abc”,
“pagePic”:http://example.com/content.jpg"
},
“员额”:[
{
“post_id”:“123456789012_123456789012”,
“演员id”:“1234567890”,
“发布者的照片”:http://example.com/photo.jpg",
“发布者姓名”:“简·多伊”,
“消息”:“听起来很酷。迫不及待地想看它!”,
“LikeCount”:“2”,
“评论”:[…],
“邮局时间”:“1234567890”
}
]
}
Java代码:
JSONObject obj=新的JSONObject(responsejsonobj);
String pageName=obj.getJSONObject(“pageInfo”).getString(“pageName”);
JSONArray arr=obj.getJSONArray(“posts”);
对于(int i=0;i
为了示例,让我们假设您有一个类Person
只有一个名称
private class Person {
public String name;
public Person(String name) {
this.name = name;
}
}
()
我个人最喜欢的是对象的JSON序列化/反序列化
Gson g = new Gson();
Person person = g.fromJson("{\"name\": \"John\"}", Person.class);
System.out.println(person.name); //John
System.out.println(g.toJson(person)); // {"name":"John"}
更新
如果您想获取单个属性,也可以使用Google库轻松完成:
JsonObject jsonObject = new JsonParser().parse("{\"name\": \"John\"}").getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John
()
如果您不需要对象反序列化,只需要获取一个属性,您可以尝试org.json(或查看上面的示例!)
()
如果您有一些表示JSON字符串(jsonString)的Java类(比如Message),那么您可以将JSON库用于:
Message message= new ObjectMapper().readValue(jsonString, Message.class);
您可以从message对象获取其任何属性。几乎所有给出的答案都需要在访问感兴趣的属性中的值之前将JSON完全反序列化为Java对象。另一种选择是使用类似于JSON的XPath并允许遍历JSON对象,而不是走这条路线
这是一个规范,JayWay的好人为该规范创建了一个Java实现,您可以在这里找到:
因此,基本上要使用它,请将其添加到您的项目中,例如:
com.jayway.jsonpath
json路径
${version}
以及使用:
String pageName=JsonPath.read(yourJsonString,“$.pageInfo.pageName”);
字符串pagePic=JsonPath.read(yourJsonString,“$.pageInfo.pa
Message message= new ObjectMapper().readValue(jsonString, Message.class);
@Generated("org.jsonschema2pojo")
public class Container {
@SerializedName("pageInfo")
@Expose
public PageInfo pageInfo;
@SerializedName("posts")
@Expose
public List<Post> posts = new ArrayList<Post>();
}
@Generated("org.jsonschema2pojo")
public class PageInfo {
@SerializedName("pageName")
@Expose
public String pageName;
@SerializedName("pagePic")
@Expose
public String pagePic;
}
@Generated("org.jsonschema2pojo")
public class Post {
@SerializedName("post_id")
@Expose
public String postId;
@SerializedName("actor_id")
@Expose
public long actorId;
@SerializedName("picOfPersonWhoPosted")
@Expose
public String picOfPersonWhoPosted;
@SerializedName("nameOfPersonWhoPosted")
@Expose
public String nameOfPersonWhoPosted;
@SerializedName("message")
@Expose
public String message;
@SerializedName("likesCount")
@Expose
public long likesCount;
@SerializedName("comments")
@Expose
public List<Object> comments = new ArrayList<Object>();
@SerializedName("timeOfPost")
@Expose
public long timeOfPost;
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(
new FileReader("c:\\file.json"));
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);
System.out.println(obj);
} catch (IOException e) {
e.printStackTrace();
}
}
}
javax.json.JsonReader jr =
javax.json.Json.createReader(new StringReader(jsonText));
javax.json.JsonObject jo = jr.readObject();
//Read the page info.
javax.json.JsonObject pageInfo = jo.getJsonObject("pageInfo");
System.out.println(pageInfo.getString("pageName"));
//Read the posts.
javax.json.JsonArray posts = jo.getJsonArray("posts");
//Read the first post.
javax.json.JsonObject post = posts.getJsonObject(0);
//Read the post_id field.
String postId = post.getString("post_id");
class MyModel {
private PageInfo pageInfo;
private ArrayList<Post> posts = new ArrayList<>();
}
class PageInfo {
private String pageName;
private String pagePic;
}
class Post {
private String post_id;
@SerializedName("actor_id") // <- example SerializedName
private String actorId;
private String picOfPersonWhoPosted;
private String nameOfPersonWhoPosted;
private String message;
private String likesCount;
private ArrayList<String> comments;
private String timeOfPost;
}
MyModel model = gson.fromJson(jsonString, MyModel.class);
implementation 'com.google.code.gson:gson:2.8.6' // or earlier versions
public class MyObj {
private PageInfo pageInfo;
private List<Post> posts;
static final class PageInfo {
private String pageName;
private String pagePic;
}
static final class Post {
private String post_id;
@JsonProperty("actor_id");
private String actorId;
@JsonProperty("picOfPersonWhoPosted")
private String pictureOfPoster;
@JsonProperty("nameOfPersonWhoPosted")
private String nameOfPoster;
private String likesCount;
private List<String> comments;
private String timeOfPost;
}
private static final ObjectMapper JACKSON = new ObjectMapper();
public static void main(String[] args) throws IOException {
MyObj o = JACKSON.readValue(args[0], MyObj.class); // assumes args[0] contains your json payload provided in your question.
}
}
com.fasterxml.jackson.databind.ObjectMapper
package com.levo.jsonex.model;
public class Page {
private PageInfo pageInfo;
private Post[] posts;
public PageInfo getPageInfo() {
return pageInfo;
}
public void setPageInfo(PageInfo pageInfo) {
this.pageInfo = pageInfo;
}
public Post[] getPosts() {
return posts;
}
public void setPosts(Post[] posts) {
this.posts = posts;
}
}
package com.levo.jsonex.model;
public class PageInfo {
private String pageName;
private String pagePic;
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
public String getPagePic() {
return pagePic;
}
public void setPagePic(String pagePic) {
this.pagePic = pagePic;
}
}
package com.levo.jsonex.model;
public class Post {
private String post_id;
private String actor_id;
private String picOfPersonWhoPosted;
private String nameOfPersonWhoPosted;
private String message;
private int likesCount;
private String[] comments;
private int timeOfPost;
public String getPost_id() {
return post_id;
}
public void setPost_id(String post_id) {
this.post_id = post_id;
}
public String getActor_id() {
return actor_id;
}
public void setActor_id(String actor_id) {
this.actor_id = actor_id;
}
public String getPicOfPersonWhoPosted() {
return picOfPersonWhoPosted;
}
public void setPicOfPersonWhoPosted(String picOfPersonWhoPosted) {
this.picOfPersonWhoPosted = picOfPersonWhoPosted;
}
public String getNameOfPersonWhoPosted() {
return nameOfPersonWhoPosted;
}
public void setNameOfPersonWhoPosted(String nameOfPersonWhoPosted) {
this.nameOfPersonWhoPosted = nameOfPersonWhoPosted;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getLikesCount() {
return likesCount;
}
public void setLikesCount(int likesCount) {
this.likesCount = likesCount;
}
public String[] getComments() {
return comments;
}
public void setComments(String[] comments) {
this.comments = comments;
}
public int getTimeOfPost() {
return timeOfPost;
}
public void setTimeOfPost(int timeOfPost) {
this.timeOfPost = timeOfPost;
}
}
package com.levo.jsonex;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.levo.jsonex.model.Page;
import com.levo.jsonex.model.PageInfo;
import com.levo.jsonex.model.Post;
public class JSONDemo {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
Page page = objectMapper.readValue(new File("sampleJSONFile.json"), Page.class);
printParsedObject(page);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void printParsedObject(Page page) {
printPageInfo(page.getPageInfo());
System.out.println();
printPosts(page.getPosts());
}
private static void printPageInfo(PageInfo pageInfo) {
System.out.println("Page Info;");
System.out.println("**********");
System.out.println("\tPage Name : " + pageInfo.getPageName());
System.out.println("\tPage Pic : " + pageInfo.getPagePic());
}
private static void printPosts(Post[] posts) {
System.out.println("Page Posts;");
System.out.println("**********");
for(Post post : posts) {
printPost(post);
}
}
private static void printPost(Post post) {
System.out.println("\tPost Id : " + post.getPost_id());
System.out.println("\tActor Id : " + post.getActor_id());
System.out.println("\tPic Of Person Who Posted : " + post.getPicOfPersonWhoPosted());
System.out.println("\tName Of Person Who Posted : " + post.getNameOfPersonWhoPosted());
System.out.println("\tMessage : " + post.getMessage());
System.out.println("\tLikes Count : " + post.getLikesCount());
System.out.println("\tComments : " + Arrays.toString(post.getComments()));
System.out.println("\tTime Of Post : " + post.getTimeOfPost());
}
}
Page Info;
****(*****
Page Name : abc
Page Pic : http://example.com/content.jpg
Page Posts;
**********
Post Id : 123456789012_123456789012
Actor Id : 1234567890
Pic Of Person Who Posted : http://example.com/photo.jpg
Name Of Person Who Posted : Jane Doe
Message : Sounds cool. Can't wait to see it!
Likes Count : 2
Comments : []
Time Of Post : 1234567890
String json = callToTranslateApi("work", "de");
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
return jsonObject.get("data").getAsJsonObject()
.get("translations").getAsJsonArray()
.get(0).getAsJsonObject()
.get("translatedText").getAsString();
class ApiResponse {
Data data;
class Data {
Translation[] translations;
class Translation {
String translatedText;
}
}
}
Gson g = new Gson();
String json =callToTranslateApi("work", "de");
ApiResponse response = g.fromJson(json, ApiResponse.class);
return response.data.translations[0].translatedText;
$.pageInfo.pageName = abc
$.pageInfo.pagePic = http://example.com/content.jpg
$.posts[0].post_id = 123456789012_123456789012
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
}
}
class PageInfo {
private String pageName;
private String pagePic;
// Getters and setters
}
PageInfo pageInfo = JsonPath.parse(jsonString).read("$.pageInfo", PageInfo.class);
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
private static final String EXTRACTOR_SCRIPT =
"var fun = function(raw) { " +
"var json = JSON.parse(raw); " +
"return [json.pageInfo.pageName, json.pageInfo.pagePic, json.posts[0].post_id];};";
public void run() throws ScriptException, NoSuchMethodException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(EXTRACTOR_SCRIPT);
Invocable invocable = (Invocable) engine;
JSObject result = (JSObject) invocable.invokeFunction("fun", JSON);
result.values().forEach(e -> System.out.println(e));
}
var fun = function(raw) {JSON.parse(raw).entries};
(JSObject) invocable.invokeFunction("fun", json);
new JSONObject(JSON).getJSONArray("entries");
mapper.readValue(JSON, Entries.class).getEntries();
ObjectMapper mapper = new ObjectMapper();
JsonNode yourObj = mapper.readTree("{\"k\":\"v\"}");
JSONObject jsonObj = new JSONObject(<jsonStr>);
String id = jsonObj.getString("pageInfo");
JSONObject jObj = new JSONObject(contents.trim());
Iterator<?> keys = jObj.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( jObj.get(key) instanceof JSONObject ) {
System.out.println(jObj.getString(String key));
}
}
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonAsString, JsonObject.class);
String pageName = jsonObject.getAsJsonObject("pageInfo").get("pageName").getAsString();
String pagePic = jsonObject.getAsJsonObject("pageInfo").get("pagePic").getAsString();
String postId = jsonObject.getAsJsonArray("posts").get(0).getAsJsonObject().get("post_id").getAsString();
JsonArray posts = jsonObject.getAsJsonArray("posts");
for (JsonElement post : posts) {
String postId = post.getAsJsonObject().get("post_id").getAsString();
//do something
}
@Model(className="RepositoryInfo", properties = {
@Property(name = "id", type = int.class),
@Property(name = "name", type = String.class),
@Property(name = "owner", type = Owner.class),
@Property(name = "private", type = boolean.class),
})
final class RepositoryCntrl {
@Model(className = "Owner", properties = {
@Property(name = "login", type = String.class)
})
static final class OwnerCntrl {
}
}
List<RepositoryInfo> repositories = new ArrayList<>();
try (InputStream is = initializeStream(args)) {
Models.parse(CONTEXT, RepositoryInfo.class, is, repositories);
}
System.err.println("there is " + repositories.size() + " repositories");
repositories.stream().filter((repo) -> repo != null).forEach((repo) -> {
System.err.println("repository " + repo.getName() +
" is owned by " + repo.getOwner().getLogin()
);
})
JsonIterator.deserialize(jsonData, int[].class);
JSONArray ja = new JSONArray(String jsonString);