是否有在 Java 中解析 Json 的通用方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26344756/
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
Is there a generic way of parsing Json in Java?
提问by Mike
I have tried with gson and Hymanson parsers unfortunately I couldn't achieve what I wanted to.
不幸的是,我尝试过 gson 和 Hymanson 解析器,但无法实现我想要的。
{
"rateName": "My Special Rate",
"adjustments": [
{
"adjustmentType": "LOAN_AMOUNT_GREATER_THAN_550K",
"rate": 0.75
},
{
"adjustmentType": "AMORTIZATION_TERM_LESS_THAN_30_YEARS",
"rate": -0.2
}
],
"errorTypes": [],
"premiumTaxs": [],
"renewalPremiums": [],
"totalInitialRate": 1.95,
"optimumPricing": false,
"miPricingVO": null,
"rateCardId": "BALS_NR",
"ratingInfoBaseRate": 1.4
}
Above is the Json I want to parse. I want to create generic methods using which I can access a value by name easily. For example:
上面是我要解析的 Json。我想创建通用方法,使用它我可以轻松地按名称访问值。例如:
- getName(rateName) - Should return 'My Special Rate'
- getNameFromArray(adjustmentType, adjustments) - Should return 'LOAN_AMOUNT_GREATER_THAN_550K'
- getName(rateName) - 应该返回“我的特价”
- getNameFromArray(adjustmentType, adjusts) - 应该返回 'LOAN_AMOUNT_GREATER_THAN_550K'
Is there a way to do this? It should be generic so that this can be applied on any Json file.
有没有办法做到这一点?它应该是通用的,以便可以应用于任何 Json 文件。
Additional info: I tried using Gson, but this parses the whole file and throws an error if it finds an array.
附加信息:我尝试使用 Gson,但这会解析整个文件,如果找到数组,则会引发错误。
JsonReader j = new JsonReader(new FileReader("Path of Json"));
j.beginObject();
while (j.hasNext()) {
String name = j.nextName();
if (name.equals("rateName")) {
System.out.println(j.nextString());
}
System.out.println(name);
}
I tried with Hymanson and encountered the same as Gson.
我用Hymanson试过,遇到和Gson一样的。
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createJsonParser("Path of Json");
while (jParser.nextToken() != JsonToken.END_OBJECT) {
System.out.println(jParser.getCurrentName());;
}
回答by meda
If you mean standard library when you say generic, then org.json
would be that library.
如果您说泛型时指的是标准库,那么org.json
就是那个库。
Altough not as intuitive as GSON or Hymanson, it is easy to use it:
虽然不像 GSON 或 Hymanson 那样直观,但它很容易使用:
JSONObject jsonData = new JSONObject(jsonString);
String rateName= jsonData.getString("rateName");//My Special Rate
To parse array you need to loop:
要解析数组,您需要循环:
JSONArray adjustments = jsonData.getJSONArray("adjustments");
for(int i = 0; i < adjustments.length(); i++){
JSONObject adjustment = adjustments.getJSONObject(i);
String adjustmentType = adjustment.getString("adjustmentType");
}
回答by Shubham Pandey
Hi You can use JASON READER , it readers the JSON and map the data into a MAP .
嗨,您可以使用 JASON READER,它读取 JSON 并将数据映射到 MAP 中。
Below is the URL to Download the JAR JASON READER.
以下是下载 JAR JASON READER 的 URL。
https://drive.google.com/open?id=0BwyOcFBoJ5pueXdadFFMS2tjLVU
https://drive.google.com/open?id=0BwyOcFBoJ5pueXdadFFMS2tjLVU
Below is the example -
下面是例子——
package com;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.JasonReader;
public class Test {
public static void main(String[] args) {
String request ="{\"rateName\": \"My Special Rate\",\"adjustments\":[{\"adjustmentType\": \"LOAN_AMOUNT_GREATER_THAN_550K\",\"rate\": 0.75},{\"adjustmentType\": \"AMORTIZATION_TERM_LESS_THAN_30_YEARS\",\"rate\": -0.2}],\"errorTypes\": [],\"premiumTaxs\": [],\"renewalPremiums\": [],\"totalInitialRate\": 1.95,\"optimumPricing\": false,\"miPricingVO\": null,\"rateCardId\": \"BALS_NR\",\"ratingInfoBaseRate\": 1.}";
//
Map<String,String> map =new HashMap<String,String>();
map=JasonReader.readJason(request,map);
//System.out.println(map);
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey()+ "=" +entry.getValue());
}
}
}
OUTPUT -
输出 -
rateCardId=BALS_NR
rateCardId=BALS_NR
adjustments|rate1=-0.2
调整|rate1=-0.2
miPricingVO=null
miPricingVO=null
adjustments|adjustmentType=LOAN_AMOUNT_GREATER_THAN_550K
调整|调整类型=LOAN_AMOUNT_GREATER_THAN_550K
adjustments|adjustmentType1=AMORTIZATION_TERM_LESS_THAN_30_YEARS
调整|调整类型1=AMORTIZATION_TERM_LESS_THAN_30_YEARS
adjustments|rate=0.75
调整|率=0.75
optimumPricing=false
最优定价=假
totalInitialRate=1.95
totalInitialRate=1.95
rateName=My Special Rate
rateName=我的特价
ratingInfoBaseRate=1.
ratingInfoBaseRate=1。
回答by Ralph
You can use the standard JsonParserwhich is part of the javax.json package. This parser is part of Java EE since version 7 and you can use this parser without any additional library.
您可以使用标准JsonParser,它是 javax.json 包的一部分。自版本 7 以来,此解析器是 Java EE 的一部分,您无需任何其他库即可使用此解析器。
The parser allows you to navigate through a JSON structure using the so called 'pull parsing programming model'
解析器允许您使用所谓的“拉式解析编程模型”浏览 JSON 结构
JsonParser parser = Json.createParser(myJSON);
Event event = parser.next(); // START_OBJECT
event = parser.next(); // KEY_NAME
String key = parser.getString(); // 'rateName'
event = parser.next(); // STRING_VALUE
String value=parser.getString(); // 'My Special Rate'
event = parser.next(); // START_ARRAY
....
But of course you need to navigate through your json data structure
但当然你需要浏览你的 json 数据结构
回答by igr
Or you can just use Jodd JSONparser. You just need to deserialize the input string and the result will be collected in regular Map
and List
.
或者你可以只使用Jodd JSON解析器。您只需要反序列化输入字符串,结果就会以常规Map
和List
.
JsonParser jsonParser = new JsonParser();
Map<String, Object> map = jsonParser.parse(input);
Simple as that - and the result is the most generic as it can be. Then just call map.get("rateName")
to get your value and so on.
就这么简单 - 结果是最通用的。然后只需致电map.get("rateName")
以获取您的价值等等。
But notice that for adjustments you can get the way you want without some util method that would iterate elements and search for the right one. If you can, change the JSON so that you dont have an array of adjustments
, but a map.
但是请注意,对于调整,您可以获得所需的方式,而无需使用某些 util 方法来迭代元素并搜索正确的元素。如果可以,请更改 JSON,以便您没有 的数组adjustments
,而是地图。
If you need specific results, just pass the type with the input string. See more about parsing features.
如果您需要特定的结果,只需将类型与输入字符串一起传递。查看有关解析功能的更多信息。