简体   繁体   English

从java中的json字符串中提取值

[英]extract value from json string in java

I have a string in json format and I want to extract certain values from that json. 我有一个json格式的字符串,我想从该json中提取某些值。 For example: 例如:

{"foo":"this is foo", "bar":{"nested_bar": "this is nested bar"} }

A user might want to print either foo or bar or both. 用户可能要打印foobar或两者都打印。

Right now, I have a simple class which can read only flat json. 现在,我有一个简单的类,它只能读取平面json。

How do I modify the following code to incorporate nested json? 如何修改以下代码以合并嵌套的json?

Another question is what is a good way to represent the tags which I want to extract as in flat json? 另一个问题是什么是表示要提取为平面json的标签的好方法? I was passing an array. 我正在传递数组。

public class JsonParser {

public static String[] tagsToExtract;



public JsonParser(String[] tags){
    tagsToExtract = tags;
}


public HashMap<String, Object> extractInformation(Text line) throws JSONException{
    HashMap<String, Object> outputHash = new HashMap<String, Object>();
    JSONObject jsn = new JSONObject(line.toString());
    for (int i =0; i < tagsToExtract.length; i++){
        outputHash.put(tagsToExtract[i],jsn.get(tagsToExtract[i].toString()));
    }
    return outputHash;

}

}

There are quite a few JSON libraries for Java that will do exactly what you want. 有很多Java JSON库可以完全满足您的要求。 A couple of the more highly regarded ones are: 一些比较受人尊敬的是:

And you can find a more in-depth discussion of the various options here: https://stackoverflow.com/questions/338586/a-better-java-json-library 您可以在此处找到有关各种选项的更深入讨论: https : //stackoverflow.com/questions/338586/a-better-java-json-library

If you are really interested in writing your own parser for it, though, the hint I will give is to take advantage of recursion. 但是,如果您真的有兴趣为其编写自己的解析器,那么我将给出的提示是利用递归。 Suppose you have a JSON object something like this: 假设您有一个类似以下内容的JSON对象:

{
    prop1: (some value),
    prop2: (some value),
    ...
}

Notice that when you start parsing the top-level object, you're doing exactly the same thing as you will be doing when you parse each value - because the values themselves can be just another JSON object. 请注意,当您开始解析顶级对象时,您将执行与解析每个值时完全相同的操作-因为这些值本身可以只是另一个JSON对象。 So a simple way to get started would be to write a parser which just gets the keys and their associated values as strings, without processing the values. 因此,一种简单的入门方法是编写一个解析器,该解析器仅将键及其关联的值作为字符串获取,而无需处理这些值。 Then, call the same algorithm again on each value - and so on, until you get to a value that is just a plain value - a string, a number, etc. 然后,对每个值再次调用相同的算法-依此类推,直到得到一个纯值(字符串,数字等)的值。

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

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