简体   繁体   English

通过对象属性进行Java json-简单访问

[英]Java json-simple accessing via object properties

One of my gripes with JSON-Simple is that if you have a heavily nested structure, then it becomes very verbose to access information. 我对JSON-Simple的了解之一是,如果您具有大量嵌套的结构,则访问信息将变得非常冗长。

Consider a trivial JSON object: 考虑一个简单的JSON对象:

{
  "announcements": {
    "inGame": {
      "playerDied": "{arg1} has died"
    }
  }
}

Should I want to print out "{arg1} has died", as I currently understand it, I must do the following: 根据我目前的理解,如果我想打印出“ {arg1}已死”,我必须执行以下操作:

 InputStreamReader inputStreamReader =
         new InputStreamReader(getClass().getResourceAsStream(configurationPath));

 JSONObject jsonObject = (JSONObject) parser.parse(inputStreamReader);

 String died = (String)((JSONObject)((JSONObject)jsonObject.get("announcements")).get("inGame")).get("playerDied");

 System.out.println(died);

As you can see, lots of casting, and lots of chaining. 如您所见,大量的转换和大量的链接。

My question is: Is there an easier way to go about this? 我的问题是: 有没有更简单的方法可以解决此问题?

For example: 例如:

String died = jsonObject.get("announcements").get("inGame").get("playerDied");

Or, even better: 或者,甚至更好:

String died = jsonObject.get("announcements.inGame.playerDied");

I feel like I'm missing something. 我觉得我想念什么。

You are looking for jsonpath for jsons on the lines of xpath for xmls. 您正在xml的xpath上寻找json的jsonpath。 Check this: 检查一下:

https://github.com/jayway/JsonPath https://github.com/jayway/JsonPath

I have used this and it works like a charm. 我用过它,它就像一个魅力。

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

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