Converting LinkedIn XML data to JSON in Java - java

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!

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();

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

Related

Java - '\' not being used to escape double quotes " in string

I have some JSON content in bytebuffer as : {\"ID\":101}"}
This content is being returned from a service invocation. I get result from that microservice in a bytebuffer. (This means - I cannot get the content changed)
Now, I need to get the json object from this buffer. I'm using this code :
ByteBuffer payloadByteBuffer = invokeResult.getPayload();
byte[] payloadByteArray = payloadByteBuffer.array();
rawJson = new String(payloadByteArray, Charset.forName("UTF-8"));
System.out.println("Raw JSon result = "+rawJson);
The string that gets printed is : "{\"ID\":101}"
Please note that '\' is getting printed within the string but it is originally used to escape double quote. So, when I try to convert this string to JSON object, I get an error :
"Missing value at 1 [character 2 line 1]"
which is probably due to '\' not being used to escape double quote character(I think).
So, My question is, how do I modify my string to treat '\' character for it's correct purpose?
I have tried replacing "\". but it didn't work. I don't know why.
I have also tried different charset encoding : US-ASCII and ASCII but got the same result.
You can try json-simple. You can use the dependency from here
P.S: Your JSON response is wrong.
ByteBuffer payloadByteBuffer = invokeResult.getPayload();
byte[] payloadByteArray = payloadByteBuffer.array();
rawJson = new String(payloadByteArray, Charset.forName("UTF-8"));
JSONParser parser = new JSONParser();
try {
JSONObject json = (JSONObject) parser.parse(rawJson);
} catch (ParseException e) {
e.printStackTrace();
}
It parses the JSON with \ in it.
How about using the apache's commons lang library?
I think it's a simple and easy way of remove your problem away.
Here is my full test code for you.
package just.test;
import java.nio.charset.Charset;
import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONObject;
import com.ibm.icu.impl.ByteBuffer;
public class UnescapeCharTest {
private static void testJSONString(final String rawJson)
{
JSONObject json = null;
try
{
json = new JSONObject(rawJson);
System.out.println("ID = "+json.get("ID"));
}
catch(org.json.JSONException je)
{
je.printStackTrace();
}
String convJson = rawJson.replace("\\", "");
try
{
json = new JSONObject(convJson);
System.out.println("ID = "+json.get("ID"));
}
catch(org.json.JSONException je)
{
je.printStackTrace();
}
convJson = StringEscapeUtils.unescapeJson(rawJson);
try
{
json = new JSONObject(convJson);
System.out.println("ID = "+json.get("ID"));
}
catch(org.json.JSONException je)
{
je.printStackTrace();
}
}
public static void main(String[] args)
{
String rawJson = "{\\\"ID\\\":101}";
testJSONString(rawJson);
String rawJson2 = null;
ByteBuffer payloadByteBuffer = ByteBuffer.wrap(rawJson.getBytes());
byte[] payloadByteArray = payloadByteBuffer.array();
rawJson2 = new String(payloadByteArray, Charset.forName("UTF-8"));
testJSONString(rawJson2);
}
}
I hope the code is right for you.
Have a good coding...

Java value of type java.lang.string cannot be converted to jsonobject

I have an API (here) that outputs a JSON string as output. I want to parse this JSON. It was working a while ago, but I might have changed something in my API or java code.
This is the code I'm using:
Here, msg is a string which contains the api response
try {
/* this prints */
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
JSONObject jObject = new JSONObject(msg);
String cleaner_id = jObject.getString("cleaner_id");
/* but this does not */
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
catch(Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
}
I'm using codeigniter framework in php.
This is the function in my php model :
public function get_cleaner($mobile, $pass){
$this->db->select("cleaner.cleaner_id, cleaner.cleaner_name, cleaner.date_of_joining, cleaner.current_address, cleaner.mobile1, cleaner.mobile2, cleaner.date_of_birth, skill.skill_name as cleaner_designation");
$this->db->from("cleaner");
$this->db->join('skill', 'cleaner.designation = skill.skill_id', 'left');
$this->db->where("mobile1", $mobile);
$this->db->where("user_pass", $pass);
$data = $this->db->get()->result_array();
return $data;
}
And this is my php controller :
public function getCleaner(){
$mobile_no = $this->input->get('mobile');
$pass = $this->input->get('pass');
if(!is_null($mobile_no) && !is_null($pass))
{
header('Content-Type: application/javascript');
$data = $this->cleaner_model->get_cleaner($mobile_no, $pass);
if(!empty($data))
echo json_encode($data[0]);
else
echo '{"cleaner_id":"-10","cleaner_name":"cleaner_not_found"}';
}
}
I have searched a lot and tried a lot of different solutions I found n web, but none of the solutions I have tried has worked out for me.
UPDATE :
this gives the error
this gives the error
But
this parses fine and gives me just key not found exception
Github sample json api and my api give the cannot convert string to json obj exception, but google maps api doesn't. Is there anything wrong with my api format ??
FIXED : I finally figured out that my api output had a leading hidden character which caused the parsing error
This is a screenshot of the error I receive (Too big a screenshot, but you get the idea...)
I tried to solve the issue, nothing worked for me and I don't know why! I have a solution but I don't know if it does make sense!
try{
HttpURLConnection conn = (HttpURLConnection) new URL("http://mridulahuja.com/api/index.php/cleaner/getCleaner?mobile=1111111111&pass=njnjhbh").openConnection();
InputStreamReader isr = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
if(line != null){
line = line.substring(line.indexOf("{"));
JSONObject obj = new JSONObject(line);
System.out.println(obj.getString("cleaner_name"));
}
reader.close();
}catch(Exception e){
System.err.println(e.getMessage());
}

Getting a Json information

I am coding in Java and I'm using the minimal-json library. I am trying to get some information from a json text (idk if it's an array).
I'm trying to access the "game" value inside "stream", but I always get a crash by nullpointer or a parseexception.
Here is the json string I'm trying to get (From the Twitch Api):
{"_links":{"self":"https://api.twitch.tv/kraken/streams/hackerc0w","channel":"https://api.twitch.tv/kraken/channels/hackerc0w"},"stream":{"_id":13817896816,"game":"Programming","viewers":13,"created_at":"2015-04-01T13:54:54Z","video_height":1080,"average_fps":59.9235368156,"_links":{"self":"https://api.twitch.tv/kraken/streams/hackerc0w"},"preview":{"small":"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-80x45.jpg","medium":"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-320x180.jpg","large":"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-640x360.jpg","template":"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-{width}x{height}.jpg"},"channel":{"_links":{"self":"https://api.twitch.tv/kraken/channels/hackerc0w","follows":"https://api.twitch.tv/kraken/channels/hackerc0w/follows","commercial":"https://api.twitch.tv/kraken/channels/hackerc0w/commercial","stream_key":"https://api.twitch.tv/kraken/channels/hackerc0w/stream_key","chat":"https://api.twitch.tv/kraken/chat/hackerc0w","features":"https://api.twitch.tv/kraken/channels/hackerc0w/features","subscriptions":"https://api.twitch.tv/kraken/channels/hackerc0w/subscriptions","editors":"https://api.twitch.tv/kraken/channels/hackerc0w/editors","videos":"https://api.twitch.tv/kraken/channels/hackerc0w/videos","teams":"https://api.twitch.tv/kraken/channels/hackerc0w/teams"},"background":null,"banner":null,"broadcaster_language":"en","display_name":"hackerc0w","game":"Programming","logo":null,"mature":false,"status":"Coding a Chatbot in C","partner":false,"url":"http://www.twitch.tv/hackerc0w","video_banner":null,"_id":41236491,"name":"hackerc0w","created_at":"2013-03-11T17:08:22Z","updated_at":"2015-04-01T17:17:44Z","delay":0,"followers":28,"profile_banner":null,"profile_banner_background_color":null,"views":2948,"language":"de"}}}
The way I got if the livestreamer was live was like this:
public static boolean isStreamLive(String channel) {
try {
URL url = new URL(TWITCH_STREAM.replace("$c$", channel)) );
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream() ));
String inputLine = br.readLine();
br.close();
JsonObject jsonObj = JsonObject.readFrom(inputLine);
return ( jsonObj.get("stream").isNull() )?false:true;
} catch (IOException e) {
return false;
}
}
And I mostly tried to copy the method above. But I have been checking the documentation of the library to know and I have been trying a lot of things.
The last was this:
public static String checkGame(String channel) {
if (!isStreamLive(channel)) return "El Estreamer esta Offline!";
try {
URL url = new URL( insertChannel(TWITCH_STREAM, channel) );
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream() ));
String inputLine = br.readLine();
br.close();
JsonObject object = JsonObject.readFrom(inputLine);
JsonValue value = object.get("stream").asObject();
String msg = value.valueOf("status").toString();
return msg;
} catch (IOException e) {
return "Algo raro paso :/ error: 3";
}
return channel;
}
You've got two main problems with the code you've shown.
The first problem that you're having is that you're trying to get the status out of the wrong nested object. You're getting the stream object from the original json and then trying to get the value of the status key from that, but in the json you've posted status is part of a nested channel object.
The structure of the json object is like so:
{
"_links": { ... },
"stream": {
...
"channel":{
"_links": { ... },
...
"status":"Coding a Chatbot in C",
...
}
}
}
... so you can't get status directly from stream, you need to get channel from stream and get the status from that.
The second problem is that you're trying to use valueOf() to pull a value out of a JsonObject. valueOf() is a static method which creates a new object based on the supplied input, so it doesn't actually use data in the object you call it on.
Calling value.valueOf("status") will completely ignore data in value and create a new JsonObject containing the string "status".
If you want to get the value of a nested object, you need to drill down to it with a series of successive get("objName").asObject() calls, and then call .get("key") to obtain the value you want:
// hardcoded for example, actually would be read from BufferedReader
String inputLine = "{\"_links\":{\"self\":\"https://api.twitch.tv/kraken/streams/hackerc0w\",\"channel\":\"https://api.twitch.tv/kraken/channels/hackerc0w\"},\"stream\":{\"_id\":13817896816,\"game\":\"Programming\",\"viewers\":13,\"created_at\":\"2015-04-01T13:54:54Z\",\"video_height\":1080,\"average_fps\":59.9235368156,\"_links\":{\"self\":\"https://api.twitch.tv/kraken/streams/hackerc0w\"},\"preview\":{\"small\":\"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-80x45.jpg\",\"medium\":\"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-320x180.jpg\",\"large\":\"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-640x360.jpg\",\"template\":\"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-{width}x{height}.jpg\"},\"channel\":{\"_links\":{\"self\":\"https://api.twitch.tv/kraken/channels/hackerc0w\",\"follows\":\"https://api.twitch.tv/kraken/channels/hackerc0w/follows\",\"commercial\":\"https://api.twitch.tv/kraken/channels/hackerc0w/commercial\",\"stream_key\":\"https://api.twitch.tv/kraken/channels/hackerc0w/stream_key\",\"chat\":\"https://api.twitch.tv/kraken/chat/hackerc0w\",\"features\":\"https://api.twitch.tv/kraken/channels/hackerc0w/features\",\"subscriptions\":\"https://api.twitch.tv/kraken/channels/hackerc0w/subscriptions\",\"editors\":\"https://api.twitch.tv/kraken/channels/hackerc0w/editors\",\"videos\":\"https://api.twitch.tv/kraken/channels/hackerc0w/videos\",\"teams\":\"https://api.twitch.tv/kraken/channels/hackerc0w/teams\"},\"background\":null,\"banner\":null,\"broadcaster_language\":\"en\",\"display_name\":\"hackerc0w\",\"game\":\"Programming\",\"logo\":null,\"mature\":false,\"status\":\"Coding a Chatbot in C\",\"partner\":false,\"url\":\"http://www.twitch.tv/hackerc0w\",\"video_banner\":null,\"_id\":41236491,\"name\":\"hackerc0w\",\"created_at\":\"2013-03-11T17:08:22Z\",\"updated_at\":\"2015-04-01T17:17:44Z\",\"delay\":0,\"followers\":28,\"profile_banner\":null,\"profile_banner_background_color\":null,\"views\":2948,\"language\":\"de\"}}}";
JsonObject object = JsonObject.readFrom(inputLine); // parse json into object
JsonObject stream = object.get("stream").asObject(); // get "stream" sub-object
JsonObject channel = stream.get("channel").asObject(); // get "channel" sub-object
JsonValue status = channel.get("status"); // get the value of "status"
String msg = status.asString();
System.out.println(msg); // Coding a Chatbot in C

Java library for searching text in JSON file

I would like to search after a given keyword in a big JSON file. Does anybody know a java library for this?
Gson could help you to parse the json file easily.
Unlike many other JSON libraries, Gson supports streaming which means you can examine the file in small chunks.
If you're just searching for a keyword, I don't see how the fact that it's JSON requires a special library. This would only help if you were looking for something particular to JSON such as a key or value.
Couldn't you just scan the file line-by-line and search for the substring?
public static boolean find(File f, String searchString) {
boolean result = false;
Scanner in = null;
try {
in = new Scanner(new FileReader(f));
while(in.hasNextLine() && !result) {
if (in.nextLine().contains(searchString))
return true;
}
}
catch(IOException e) {
e.printStackTrace();
}
finally {
try { in.close() ; } catch(Exception e) { /* ignore */ }
}
return false;
}
from http://technojeeves.com/joomla/index.php/free/109-search-for-string-in-text-file-in-java.
You can find json library it here.
Search for JSONArray and JSONObject
http://www.json.org/javadoc/org/json/JSONArray.html
it's pretty easy to work with them.

JAX-RS #PathParam How to pass a String with slashes, hyphens & equals too

I am new to JAX-RS and I am trying to use Jersey to build a simple RESTful Webservice.
I have 2 questions. Please clarify these:
I am trying to have my simple webservice like this URL http://localhost:8080/SampleJersey/rest/inchi/InChIName
The InChIName is a string like this InChI=1S/C9H8O4/c1-6(10)13-8-5-3-2-4-7(8)9(11)12/h2- 5H,1H3,(H,11,12). How do I pass this as a #PathParam, I mean a normal String is working fine but here there are slashes,hyphens, and commas. How do I make it to ignore these. I tried putting it in quotes, but that didnt work. How should I do this?
I need to pass that InChI to another webservice and that returns an XML as an output and I want to display that XML output as my Webservice's output. If I have #Produces("application/xml") will it work?
This is my code:
#Path("/inchi")
public class InChIto3D {
#GET
#Path("{inchiname}")
#Produces("application/xml")
public String get3DCoordinates(#PathParam("inchiname")String inchiName) {
String ne="";
try{
URL eutilsurl = new URL(
"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?"
+ "db=pccompound&term=%22"+inchiName+"%22[inchi]");
BufferedReader in = new BufferedReader(
new InputStreamReader(eutilsurl.openStream()));
String inputline;
while ((inputline=in.readLine())!=null)
ne=ne+inputline;
}catch (MalformedURLException e1) {
}catch (IOException e2){
}
return ne;
}
}
This is how you enable slashes in path params:
#Path("{inchiname : .+}")
public String get3DCoordinates(#PathParam("inchiname")String inchiName)
Tomcat does not Accept %2F in URLs: http://tomcat.apache.org/security-6.html. You can turn off this behavior.
The following should work:
#GET
#Path("{inchiname : (.+)?}")
#Produces("application/xml")
public String get3DCoordinates(#PathParam("inchiname")String inchiName) {
(This is sort of mentioned in another answer and comment, I'm just explicitly putting it in a separate answer to make it clear)
The parameters should be URL encoded. You can use java.net.URLEncoder for this.
String encodedParam = URLEncoder.encode(unencodedParam, "UTF-8");
The / will then be translated to %2F.
I got this to work using #QueryParam() rather than #PathParam.
#Path("/inchi")
public class InChIto3D {
#GET
//#Path("{inchiname}")
#Produces("application/xml")
public String get3DCoordinates(#QueryParam("inchiname") String inchiName) {
String ne="";
try{
URL eutilsurl = new URL(
"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?"
+ "db=pccompound&term=%22"+inchiName+"%22[inchi]");
BufferedReader in = new BufferedReader(
new InputStreamReader(eutilsurl.openStream()));
String inputline;
while ((inputline=in.readLine())!=null)
ne=ne+inputline;
}catch (MalformedURLException e1) {
}catch (IOException e2){
}
return ne;
}
}
Thus the URL structure would be like this http://myrestservice.com/rest/inchi?inchiname=InChIhere
With #PathParam I read in the API that it will not accept slashes. I am wondering if I can use any Regular Expression in #Path just to ignore all slashes in the string that would be entered in quotes" ".

Categories

Resources