views:

32

answers:

2

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&lt;/url&gt;  
  </site-standard-profile-request>

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&lt;\/url&gt;  <\/site-standard-profile-request><\/person>"] not found.

Any help is appreciated, thanks!

A: 

It looks like you are using the wrong object and method. JSONObject.getJSONObject() expects you to provide a key to lookup an object, not an arbritrary XML string.

You don't have a key that matches that XML string, so the lookup is failing and you get the exception that the object (with the specified key) was not found.

You are trying to parse XML and serialize as JSON.

I believe that you could use XML.toJSONObject

Mads Hansen
A: 

Mads, that did just the trick! Thank you so much, I knew there was a very simple solution that I just wasn't seeing. Here is the magical line that converts an XML string to JSON:

String ret = XML.toJSONObject(aStringOfXml).toString();
jeremyckahn