-1

So I can get two possible outputs out of an API, I can choose what i want, the thing is i need to parse it in my java code and get the Value at the gm tag, or throw an Exception if there is no gm tag, and get one value out of it, the librarys I'm using are: org.json,org.apache.commons.configuration, i can use what i want as long as it can be injected with Maven. Throwing the Exception etc. is simple, accessing the value on the other hand gets me, if there is no simple solution i'll just write a while loop that is searching for the tag

The XML-String looks like this:

<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>

The JSON-String looks like this:

{
    "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
                    }
                ]
            }
        ]
    }
}

I will use whatever is more simple,I would also be happy if some1 can point out an alternativ library because org.json seems overly complicated.

I just can't wrap my head around it, i need to access the "gm" value, or throw an Exception if there is no such value.

Cnoffel
  • 3
  • 3

4 Answers4

1

Use Gson json parser and choose the json style. Json is the future. That thread will help you a lot, brother in arms. How to get a value from gson object by key

Community
  • 1
  • 1
strash
  • 1,291
  • 2
  • 15
  • 29
  • 1
    Can you maybe give me a short code example on how to access the value with Gson? I'm reading https://sites.google.com/site/gson/gson-user-guide that doesn't seem to help much – Cnoffel May 05 '17 at 17:40
  • Yes updated my answer and there is everything you need. Read the last 2 lines of their answer. – strash May 05 '17 at 17:44
0

I can propose it like so easy approach for working. For example for JSON scheme:

[{"T":["",""]},
 {"C":["asdg","1"]},
 {"C":["asdgdfgf","2"]}
]

in the code of parsing you can check needed tag by conditions if (cp.containsKey("C")):

   import org.json.simple.*;
    ...

    String fileDictName = "..";
    ...
    JSONParser parser = new JSONParser();
            try {

                Object obj = parser.parse(new FileReader(fileDictName));
                JSONArray cons = (JSONArray) obj;
                Iterator<JSONObject> itCons = cons.iterator();
                while (itCons.hasNext()) {
                    JSONObject cp = (JSONObject) itCons.next();
                    if (cp.containsKey("T")) {
                        JSONArray tbl1 = (JSONArray) cp.get("T");
                        boolean first = true;
                        Iterator<String> ittbl = tbl1.iterator();
                        while (ittbl.hasNext()) {
                            String str = ittbl.next();
                            if (first) {
..                                inttabl++;
                                first = false;
                            } else {
                                ...
                            }
                        }
                    }

                    if (cp.containsKey("C")) {
                        JSONArray cons1 = (JSONArray) cp.get("C");
                        boolean first = true;
                        Iterator<String> itCons1 = cons1.iterator();
                        while (itCons1.hasNext()) {
                            String str = itCons1.next();
                            if (first) {
    ...
                                intkeywords++;
                                first = false;
                            } else {
    ...
                            }
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

To use the same data in XML scheme:

-<dictionary>    
-<typeof>
    <tname id="0">sdfas|dfdfd</tname>
    </typeof>

-<concept id="0">    
<con_name>asdg</con_name>    
<subjectOf>dfdfd</subjectOf>    
</concept>    
-<concept id="1">    
<con_name>asdgdfgf</con_name>    
<objectOf>dfdfd</objectOf>    
</concept>
</dictionary>

you can use like example:

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 {
...
        }
Vasyl Lyashkevych
  • 1,920
  • 2
  • 23
  • 38
  • Ok, so what is that doing exactly? Why do i need to addRows or setValues, if i want to access the Value? I got the JSON String already from an InputStreamReader + URL – Cnoffel May 05 '17 at 17:54
  • 1
    I show you one example which you can easy to use. You can adapt it for your soft. You don't need to addRows, or something. I am trying to show you the main structure for working – Vasyl Lyashkevych May 05 '17 at 17:59
0

For your JSON string you can try below code :

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");
        }
    }
}

Library used : org.json

For XML part, you can simply convert XML to JSONObject using XML.toJSONObject(XML_TEXT) and then you can use above code as it is.

Nishesh Pratap Singh
  • 2,131
  • 2
  • 13
  • 20
0

I would go with a json path library with a simple $.report.foods[0].nutrients[0].gm if you only need to check if there's at least one food with at least one nutrient with the gm element (you can of course use more complex paths based on your needs)

look for examples here https://github.com/json-path/JsonPath

simple example

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

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

I don't remember if you get an exception in case the path doesn't exist or whatever but that's very easy to test yourself

Emanuele Ivaldi
  • 1,332
  • 10
  • 15