Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中的JSON/XML解析_Java_Json_Xml - Fatal编程技术网

java中的JSON/XML解析

java中的JSON/XML解析,java,json,xml,Java,Json,Xml,所以我可以从一个API中获得两个可能的输出,我可以选择我想要的,问题是我需要在java代码中解析它,并在gm标记处获取值,或者如果没有gm标记,则抛出一个异常,并从中获取一个值,我使用的库是:org.json、org.apache.commons.configuration,只要可以注入Maven,我就可以使用我想要的东西。抛出异常等是很简单的,另一方面,访问值会让我受益匪浅,如果没有简单的解决方案,我将只编写一个while循环来搜索标记 XML字符串如下所示: <report sr="2

所以我可以从一个API中获得两个可能的输出,我可以选择我想要的,问题是我需要在java代码中解析它,并在gm标记处获取值,或者如果没有gm标记,则抛出一个异常,并从中获取一个值,我使用的库是:org.json、org.apache.commons.configuration,只要可以注入Maven,我就可以使用我想要的东西。抛出异常等是很简单的,另一方面,访问值会让我受益匪浅,如果没有简单的解决方案,我将只编写一个while循环来搜索标记

XML字符串如下所示:

<report sr="28" groups="All groups" subset="All foods" end="0" start="0" total="0">
    <foods>
        <food ndbno="45149194" name="AHOLD, DIET GINGER BEER, UPC: 688267176883" weight="355.0" measure="1.0 BOTTLE">
            <nutrients>
                <nutrient nutrient_id="208" nutrient="Energy" unit="kcal" value="0" gm="0.0"/>
            </nutrients>
        </food>
    </foods>
</report>
{
    "report": {
        "sr": "28",
        "groups": "All groups",
        "subset": "All foods",
        "end": 0,
        "start": 0,
        "total": 0,
        "foods": [
            {
                "ndbno": "45149194",
                "name": "AHOLD, DIET GINGER BEER, UPC: 688267176883",
                "weight": 355.0,
                "measure": "1.0 BOTTLE",
                "nutrients": [
                    {
                        "nutrient_id": "208",
                        "nutrient": "Energy",
                        "unit": "kcal",
                        "value": "0",
                        "gm": 0.0
                    }
                ]
            }
        ]
    }
}
我将使用更简单的方法,如果有人能指出alternativ库,我也会很高兴,因为org.json看起来太复杂了


我只是无法理解它,我需要访问“gm”值,如果没有这样的值,则抛出异常。

使用Gson json解析器并选择json样式。Json是未来。那根线会帮你很多忙的,兄弟

我可以提出这样一种简单的工作方法。 例如,对于JSON方案:

[{"T":["",""]},
 {"C":["asdg","1"]},
 {"C":["asdgdfgf","2"]}
]
在解析代码中,如果(cp.containsKey(“C”),您可以按条件检查所需的标记:


对于JSON字符串,您可以尝试以下代码:

JSONObject jsonobj = new JSONObject(str);
JSONArray foodArray = jsonobj.getJSONObject("report").getJSONArray("foods");
for(int i = 0;i<foodArray.length();i++){
    JSONArray nutrientsArray = foodArray.getJSONObject(i).getJSONArray("nutrients");
    for(int j = 0;j<nutrientsArray.length();j++){
        JSONObject nutrientObj = nutrientsArray.getJSONObject(j);
        if(nutrientObj.has("gm")){
            System.out.println("do what you want in case it has gm");
            //do what you want in case it has gm
        }else{
            //do what you want in case it do not have gm
            System.out.println("do what you want in case it not gm");
        }
    }
}
JSONObject jsonobj=新的JSONObject(str);
JSONArray foodArray=jsonobj.getJSONObject(“报告”).getJSONArray(“食品”);

对于(int i=0;i我将使用一个json路径库,其中包含一个简单的$.report.foods[0].nutrients[0].gm,如果您只需要检查是否有至少一种食物包含至少一种营养素和gm元素(当然,您可以根据需要使用更复杂的路径)

在这里寻找例子

简单例子

String json = "{yor json here}";
Object document = 
Configuration.defaultConfiguration().jsonProvider().parse(json);

String gmValue = JsonPath.read(document, "$.report.foods[0].nutrients[0].gm");

我不记得在路径不存在或其他情况下,你是否会遇到异常,但这很容易测试你自己

你能给我一个简短的代码示例,说明如何使用Gson访问值吗?我正在阅读这篇文章,这似乎帮不上忙。他们更新了我的答案,你需要什么。阅读他们答案的最后两行。好的,那么这到底是在做什么呢?如果我想访问值,为什么我需要添加行或设置值?我已经从InputStreamReader+Url中获得了JSON字符串。我向您展示了一个易于使用的示例。您可以根据您的软件对其进行调整。您不需要添加行或其他内容。我试图向您展示工作的主要结构
import org.xml.sax.*;
...
       try {
                SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser saxParser = factory.newSAXParser();

                DefaultHandler handler = new DefaultHandler() {

                    boolean bdictionary = false;
                    boolean btypeof = false;
...

                    @Override
                    public void startElement(String uri, String localName, String qName,
                            Attributes attributes) throws SAXException {

                        //  System.out.println("Start Element :" + qName);
                        sV = qName;

                        if (qName.equalsIgnoreCase("dictionary")) {
                            bdictionary = true;
                        }

                        if (qName.equalsIgnoreCase("typeof")) {
                            btypeof = true;
                        }

                        if (qName.equalsIgnoreCase("tname")) {
                            btname = true;
                        }

                        if (qName.equalsIgnoreCase("concept")) {
                            bconcept = true;
                        }

                        if (qName.equalsIgnoreCase("con_name")) {
                            bcon_name = true;
                        }

                        if (qName.startsWith("subjectOf")) {
                            bsubjectof = true;
                        }
                        if (qName.startsWith("objectOf")) {
                            bobjectof = true;
                        }

                    }

                    @Override
                    public void endElement(String uri, String localName,
                            String qName) throws SAXException {
                        //System.out.println("End Element :" + qName);
                    }

                    public void saveTuple(String strT) {
        ...
                    }

                    public void saveKeyw(String strT) {
..                        
}


...


                    @Override
                    public void characters(char ch[], int start, int length) throws SAXException {

                        if (bdictionary) {
                            //  System.out.println("dictionary : " + new String(ch, start, length));
                            bdictionary = false;
                        }

                        if (btypeof) {
                            //  System.out.println("id : " + new String(ch, start, length));
                            btypeof = false;
                        }

...

                    }

                };
                saxParser.parse(fileDictName, handler);
            } catch (ParserConfigurationException | SAXException | IOException e) {
            }

        } else {
...
        }
JSONObject jsonobj = new JSONObject(str);
JSONArray foodArray = jsonobj.getJSONObject("report").getJSONArray("foods");
for(int i = 0;i<foodArray.length();i++){
    JSONArray nutrientsArray = foodArray.getJSONObject(i).getJSONArray("nutrients");
    for(int j = 0;j<nutrientsArray.length();j++){
        JSONObject nutrientObj = nutrientsArray.getJSONObject(j);
        if(nutrientObj.has("gm")){
            System.out.println("do what you want in case it has gm");
            //do what you want in case it has gm
        }else{
            //do what you want in case it do not have gm
            System.out.println("do what you want in case it not gm");
        }
    }
}
String json = "{yor json here}";
Object document = 
Configuration.defaultConfiguration().jsonProvider().parse(json);

String gmValue = JsonPath.read(document, "$.report.foods[0].nutrients[0].gm");