2
{
    "CollegeResponse": {
        "departmentDetails": {
            "id": 42,
            "departmentName": "computer science",
            "labDetails": {
                "id": 21,
                "description": "machine learning",
                "assistant": {
                    "empid": 201101,
                    "isPermanent": false
                }
            },
            "affilated": false
        }
    }
}


responseInString = response.getEntity(String.class);
JSONObject json = new JSONObject(responseInString);
String id = json.getJSONObject("CollegeResponse").getJSONObject("departmentDetails").getString("id");

Currently I am using this procedure to validate json response with db. But in case my json response is big and I need to parse an each value with db, how can I write a generic method or does it already exist, like getvalue(jsondata`) which accepts a json object finds the levels i need to iterate and gets the value. I have a lot of different json responses so a generic method which helps me retrieve the json value would make my job easy.

1
  • Can a json tokenizer help ?
    – Aayush
    Jan 30, 2013 at 7:32

2 Answers 2

1

I have used string tokenization to retrieve values from a json object. You need to provide the json object and field value to get the value for a particular key. Can we optimize it any further ?

package javaapplication1;

import java.util.StringTokenizer;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class Tokenization {

    public static void main(String args[]) {
        JSONObject parentData = new JSONObject();
        JSONObject childData = new JSONObject();
        parentData.put("command", "dance");
        parentData.put("uid", "123123123");
        childData.put("uid", "007");
        childData.put("username", "sup");
        childData.put("password", "bros");
        parentData.put("params", childData);
        System.out.println(parentData);
        String result = getValue(parentData, "params.uid");
        System.out.println("Result:" + result);
    }

    public static String getValue(JSONObject inputJson, String field) {
        String resultValue = null;
        try {
            StringTokenizer stJson = new StringTokenizer(field, ".");
            int count = stJson.countTokens();
            JSONObject objecStore = new JSONObject();
            objecStore = inputJson;
            while (stJson.hasMoreTokens()) {
                String st = stJson.nextToken();
                if (count > 1) {
                    JSONObject objNode = objecStore.getJSONObject(st);
                    count--;
                    objecStore = objNode;
                } else {
                    System.out.println(st);
                    resultValue = objecStore.getString(st);
                }
            }

        } catch (JSONException e) {
        }
        return resultValue;
    }
}
0

I think you mean "parse" rather than "validate" - your objective being to use the data in your Java code. The JAX/B standard defines a way a mapping between a Java Object and an equivalent JSON representation. In your example you would have classes such as CollegeResponse and DepartmentDetails.

Setting up these Java Classes is a little bit of tedious work if you're doing it by hand, you need to create the properties in each class corresponding to each JSON attribute, and then annotate the class to tell JAX/B about the correspondance.

This article gives a description of how to do that.

There do appear to be Eclipse tools that automate this manual drudgery.

Once that's complete the code to convert the JSON to Java becomes

JAXBContext context = JAXBContext.newInstance(CollegeResponse.class);
Unmarshaller um = context.createUnmarshaller();
CollegeResponse college = (CollegeResponse ) um.unmarshal(
          /* some Reader for the JSON string */ );

The net effect is that rather than writing lots of little getJSONObject() calls, you invest in setting up corresponding classes, this should result in nicely structured code, where the processing of the data, that is the real business logic, is separated from the parsing code, which I view as "plumbing".

2
  • @djna - The JAXB specification defines Java to XML binding, not JSON.
    – Perception
    Jan 30, 2013 at 7:28
  • I should clarify, as Perception says, JAXB was originally about mapping between Java and XML, pragmatically may implementations of JAXB also support mapping to to JSON: for example wiki.fasterxml.com/JacksonJAXBAnnotations. I confess I've been using this stuff so routinely I've been taking the capability for granted.
    – djna
    Jan 30, 2013 at 7:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.