JSON parsing in java - java

I have no idea how to parse JSON in java(or anything else). I've seen some tutorials but I can't get it straight.
I am trying to get title="Fabiola Jean and Laurent Lundy commented on a photo that you're tagged". All I need is to know how to create a getTitle() method
this is the JSON I want to parse:
Connection[data=[Notification[id=notif__161136848 metadata=null
title=Fabiola Jean and Laurent Lundy commented on a photo that you're tagged in. type=null]]
nextPageUrl=https://graph.facebook.com/811204509/notifications?fields
=title&value=1&format=json&redirect=1&access_token=MY_TOKEN&__paging_token=
notif__161136848
previousPageUrl=https://graph.facebook.com/811204509/notifications?fields=title
&value=1&format=json&redirect=1&access_token=MY_TOKEN&limit=5000&since=1342109329&
__paging_token=notif__161136848&__previous=1 next=true previous=true]

First, the code you put in your question is absolutely not valid JSON. I'm not quite sure what it is, and it does not appear to be easily parsable.
Assuming you are trying to parse actual JSON you almost certainly want to use a 3rd party library instead of writing the code using string manipulation functions.
Gson would be my first recommendation, and Jackson is another alternative you might want to look at.

Related

Convert an org.bson.Document to an org.bson.BasicBSONObject in Java?

I have a String in Pentaho Data Integration (PDI) a.k.a. Kettle, in a transformation's UDJC step.
So using Java, I need to take that String which contains JSON from MongoDB, and put it into a BasicBSONObject. (I can use import statements but I can't install things as part of a solution.)
I got the String into an org.bson.Document so it seems like the hard part's over, but I still can't figure out how to convert one type of bson to another here, resulting in an object of type org.bson.BasicBSONObject
This errors out on the last line:
import org.bson.Document;
...
String mongoResultString = get(Fields.In, "mongoAsset").getString(r);
Document mongoResultDoc = Document.parse(mongoResultString );
BasicBSONObject mongoResult = (BasicBSONObject) mongoResultDoc;
Tried ecosia, google, and searching Stack Overflow.
Thanks.
There is a BasicDBObject#parse method in MongoDB Java Driver library, which is most probably present on the classpath of your application. This method, according to the documentation, parses a string in MongoDB Extended JSON format to a BasicDBObject.
You can use it directly and skip the Document parsing step.
BasicBSONObject mongoResult = BasicDBObject.parse(mongoResultString);
After much wasted time with multiple online resources suggesting to use org.bson.Document and then they become too busy being BSON evangelists to mention the actual solution part... facepalm ...I finally found out this is actually quite simple. Parse the String into a JSON and immediately cast to a BasicBSONObject:
BasicBSONObject mongoResult = (BasicBSONObject) com.mongodb.util.JSON.parse(mongoResultString);
That worked for me because I already know mongoResultString is valid JSON because it came straight from Mongo, but otherwise could presumably wrap it in a try block.
Not sure of performance differences or gotchas, but now that I know what to look for, I've also seen evidence of Eugene's solution being workable. (Also shorter. Accepting that as the solution.) Thanks very much!

Why is the JSON content property treated special when converted to XML?

I'm using the available transformation functions in the org.json library to transform json to xml. It's very simple to do like this.
String xmlStr = XML.toString(new JSONObject(jsonStr));
Everything was perfect until I needed to process some json that contained the content property like this.
{
"content": "X",
...
}
I expected this to convert to
<content>X</content>
but instead it converts to simply X without the opening and closing tags. So I checked the source code for XML.toString and "content" is treated special. The comment in the code says this.
// Emit content in body
I Googled and also found this.
Content text may be placed in a "content" member
However I can't find an explanation of what this is all about. What's the purpose and why would someone want this to be treated in a special way? Also If you can point me to a good explanation that would be quite helpful.
This seems to be a non-optimal implementation decision. The most recent discussion have taken place in org.json issue #394:
"content" is an unfortunately-named keyword in the XML <-> Java transformation. For the history of this issue, please see #344, #286, and #108. For more information about how the keyword works, see XMLTest.java contentOperations() in https://github.com/stleary/JSON-Java-unit-test.
No objection if someone wants to propose a workaround along the lines of #108, or any other approach that does not break existing applications.
There is underscore-java library with static method U.jsonToXml(json). It supports content key name. I am the maintainer of the project.
{
"content": "X"
}
Output:
<?xml version="1.0" encoding="UTF-8"?>
<content>X</content>

Explain the functionality of JSON

I think it is better to understand why I have so many problems with JSON that I explain you what my goal is:
I work with Googles App Engine. There I want to store data. The data looks like
user - username
question - question
date1 - date1
date2 - date2
An Android App have the "simple" function to: Send the data which the user has entered and reviece the data from the complete database.
Ok, fine.
So I searched for a good "API" for that. The question about that was: "how can I read the data" and "how can I sent". The "simple" anwere was: use JSON.. . Many people say's that to me.
The first step was to show the data from the database. I write in python that:
json.dumps({"info": [{'user': 'username1', 'question': 'question1', 'date1':'date1', 'date2':'date1'}, {'user': 'username2', 'question': 'question2', 'date1':'date2', 'date2':'date2'}]})
It works. On the Client site I write in Java these:
JSONObject ob = new JSONObject(result);
JSONArray arNames = ob.getJSONArray("info");
for(int i = 0; i < arNames.length(); i++){
JSONObject c = arNames.getJSONObject(i);
Log.i("name", c.getString("name"));
Log.i("frage", c.getString("question"));
}
These works also.
But (and now the main question about the thread!):
Why we use JSON to format?! Why? I can with this data an other simple "API" without the JSON libarys and classes.
Example:
If I say on the Server site only:
!user:user;question:question;date1:date1;date2:date2
!user:user1;question:question1;data2:date3;date2:date3
... and so one...
On the Client site the same:
[READ THE DATA WITH ClientHTTP]
String[] all = result.Split("!");
for(int i = 0; i<all.length; i+= 1)
{
String[] split2 = all[i].Split(";");
String[] user = split2[0].Split(":");
// user[1] holds now the user
String[] split3 = split2[1].Split(";");
String[] questinn = split3.Split(":");
// question[1] holds now the question
... AND SO ONE!
So, why I use JSON? My option or example do the same. But with my own Syntax..
Thank you for help
JSON is a standard format and it's implementations make it easy to use -- No split() and other stuff necessary. Also, it's supported by all kinds of programming languages (like Python and Java in your own example) and so it provides a simple way to exchange data between completly different systems.
And it's well thought out and could for example also handle questions with ':' or ';' in it. A case where your suggested solution would fail.
I am not sure with JSON but there alreday was a thread explaining JSON (google knows everything). Maybe you can find some help here:
What is JSON and why would I use it?
http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/
EDIT: I forgot to answer the question why not to use your own function. Of course you can use it and it works. But a lot of services give a JSON to you. It is like a standard. Furthermore there is an JavaClass. So you do not have to do the work which others already have done (see: http://goo.gl/9X4HU)
Best regards
Don't do it by hand, it's error-prione and violates DRY (don't repeat yourself). Instead:
On server use a REST framework that automatically produces JSON. For example RESTEasy. Search the net for examples.
On Android use either built in support for JSON or better use on of well-known and tested libs: GSON or Jackson. See some speed comparisons. Alternativelly you can use Spring Android, which mashes networking+JSON in one easy to use package.
I use JSON in Android because it is lightweight data format which I can easily convert to Java objects using this google library.
You always have 2 possibilities - to use some library, or to write the code by yourself. I'm not saying that using the library is always an option, but in many cases it can save your time and reduce errors. It's up to you to decide.

JSON-lib escaping / preserving strings

I am using JSON-lib library for java http://json-lib.sourceforge.net
I just want to add simple string which can look like JSON (but i do not want library to automatically figure out that it might be json and just to treat it as string). Looking into source of library I can't find the way to do it without ugly hacks.
example:
JSONObject object = new JSONObject();
String chatMessageFromUser = "{\"dont\":\"treat it as json\"}";
object.put("myString", chatMessageFromUser);
object.toString() will give us {"myString":{"dont":"treat it as json"}}
and i want just to have {"myString":"{\"dont\":\"treat it as json\"}"}
How to achieve it without modifying source code ? I am using this piece of code as transport for chat messages from users - so it works OK for normal chat messages, but when user will enter JSON format as message it will break it because of default behavior of JSON-lib described here.
If I understand question correctly, I think json-lib is unique in its assumption of a String being passed needing to be parsed. Other libs typically treat it as String to include (with escaping of double-quotes and backslashes as necessary), i.e. work as you would expect.
So you may want to consider other libraries: I would recommend Jackson, Gson also works.
json-simple offers a JSONObject.escape() method.

How do I convert a Java Hashtable to an NSDictionary (obj-C)?

At the server end (GAE), I've got a java Hashtable.
At the client end (iPhone), I'm trying to create an NSDictionary.
myHashTable.toString() gets me something that looks darned-close-to-but-not-quite-the-same-as [myDictionary description]. If they were the same, I could write the string to a file and do:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:tmpFile];
I could write a little parser in obj-C to deal with myHashtable.toString(), but I'm sort-of hoping that there's a shortcut already built into something, somewhere -- I just can't seem to find it.
(So, being a geek, I'll spend far longer searching the web for a shortcut than it would take me to write & debug the parser... ;)
Anyway -- hints?
Thanks!
I would convert the Hashtable into something JSON-like and take it on the iPhone side.
Hashtable.toString() is not ideal, it will have problem with spaces, comma and quotation marks.
For JSON-to-NSDictionary, you can find the json-framework tools under http://www.json.org/
As j-16 SDiZ mentioned, you need to serialize your hashtable. It can be to json, xml or some other format. Once serialized, you need to deserialize them into an NSDictionary. JSON is probably the easiest format to do this with plenty of libraries for both Objective-C and Java. http://json.org has a list of libraries.

Categories