Linked Questions

Popular Questions

Converting LinkedIn XML data to JSON in Java

Asked by At

I am making a LinkedIn app that is primarily written JavaScript and Flash, but all of the data comes from a Java proxy. I need the data to be in JSON, and unfortunately LinkedIn only supports XML. The best solution is to convert XML to JSON on the server before sending it back to the client, but admittedly my Java skills are not strong. I have code that looks like it should work, but I get a JSONObject exception.

I am using the org.json package to manipulate the XML: http://json.org/java/

Here is the Java snippet that tries to convert XML to JSON. It's not pretty, but I'm just trying to make some headway with converting the data:

public static String readResponse(HttpResponse response) {
    System.out.println("Reading response...");

    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        String readLine;
        String innhold = "";

        while (((readLine = br.readLine()) != null)) {
            innhold += readLine;
        }

        try {
            JSONObject myJ = new JSONObject();
            String ret = myJ.getJSONObject(innhold).toString();
            System.out.println(ret);

            return ret;
        } catch (Exception e) {
            System.out.println(e);
        }

        return innhold;
    } catch (IOException e) {
        System.out.println(e);
        return null;
    }
}

Here is data very similar to what I am trying to convert:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person> 
    <first-name>First</first-name>  
    <last-name>Last</last-name>  
    <headline>My Profile</headline>      
    <site-standard-profile-request>    
    <url>http://www.linkedin.com/profile</url>  
    </site-standard-profile-request>
</person>

And here is the exception I am getting:

org.json.JSONException: JSONObject["<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><person>  <first-name>First<\/first-name>  <last-name>Last<\/last-name>  <headline>My Profile<\/headline>  <site-standard-profile-request>    <url>http://www.linkedin.com/profile<\/url>  <\/site-standard-profile-request><\/person>"] not found.

Any help is appreciated, thanks!

Related Questions