I am currently writing an application in Java, and am struggling to extract the values from a String which is in a JSON format.
Could someone help me with the easiest, most simplest way to extract data from this string? I'd prefer not to use external library if at all possible.
{"exchange":{"status":"Enabled","message":"Broadband on Fibre Technology","exchange_code":"NIWBY","exchange_name":"WHITEABBEY"},"products":[{"name":"20CN ADSL Max","likely_down_speed":1.5,"likely_up_speed":0.15,"availability":true....
Could someone explain how I could return the "likely down speed" of "20CN ADSL Max for example?
Thanks
Currently , there is no way in Java to parse json without an external lib (or your own implementation).
The org.json library is a standard when working with JSON.
You can use this snippet along with the library to achieve what you asked:
JSONObject obj = new JSONObject(" .... ");
JSONArray arr = obj.getJSONArray("products");
for (int i = 0; i < arr.length(); i++) {
String name = arr.getJSONObject(i).getString("name");
if ( name.equals("20CN ADSL Max") ) {
String s = arr.getJSONObject(i).getString("likely down speed");
}
}
Hope this helps.
For sure it's possible to do the parsing yourself, but it'll be much faster if you rely upon an existing library such as org.json.
With that, you can easily convert the string into a JSON object and extract all the fields you need.
If an existing library is not an option, you'll need to build yourself the tree describing the object in order to extract the pair key-values
While this may seem like a very simple, straightforward task, it gets rather complicated rather quickly.
Check out the SO thread How to parse JSON in Java. There is unfortunately not a single, clear solution to that question as shown in that thread. But I guess the org.json library seems to be the most popular solution.
If your application needs to handle arbitrary JSON, I would advise against trying to build your own parser.
Whatever your objections are to using an external library, get over them.
Related
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.
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.
I have a json data that I need to be parse in java The data is in the form
["string1","string2","string3",...]
Any idea how I can do that?
You can use JacksonJSON. For a good tutorial, have a look here.
You can use GSON api and use the code as below
Type type = new TypeToken<Collection<String>>(){}.getType();
List<String> results = new Gson().fromJson(json, type);
http://code.google.com/p/google-gson/
It depends a bit on how complete you want toe JSON parsing to be. If the above example is representative of all you expect, you might as well do some good old string parsing with indexOf and split.
If you want more complete JSON parsing, I'd suggest looking at the official json.org site and their Java page
I want to create a string which will look like the following:
"[{"product_id":"123","name":"stack"},{"product_id":"456","name":"overflow"}]"
I have the product_id and name in two arrays. How can I create the above type of string most efficiently?
This looks like JSON. You should use a JSON library.
There are plenty out there (see this page, scroll almost to the end), but
Gson (Sample Usage) or
Jackson (Sample Usage)
are the ones I'd use.
If it turns out you already have a List<ProductInformation>, then the default serialization with flexjson with an exclude will give you the string:
String jsonResult = new JSONSerializer().exclude("*.class").serialize(listOfProductInformation);
Regarding performance, your best bet is to use a good profiler to look at your overall application. This will identify your true hotspots/bottlenecks and if it turns out this serialization process is a hotspot, you can spend time tuning as #Ali mentions and running it back through the profiler or performance test harness to measure the impact.
You may want to have a look on the Java String Formatter:
http://download.oracle.com/javase/6/docs/api/java/util/Formatter.html
I'm assuming you have 2 arrays one containing and product_id and the other containing the values and both of these are in correct order.
I would create my own java object (POJO) that had two fields product_id and name then take your two arrays and create one array (or list) of POJOs each POJO containing the product_id and name. Then I would just use Jackson or Gson to create my JSON.
These libraries give you a JSON representation of a Java Objects, so in this case you will have to make sure that you have a list or even an array of objects which contain your product_id and name.
If you insist on doing it the hard-way (or no external library way), then I would create a template String and repeatedly call replace on it and add it to a StringBuffer. The StringBuffer is important if the string can be very large. Something like:
String template = "{\"product_id\":\"productId\",\"name\":\"productName\"}";
StringBuffer result = new StringBuffer("[");
for(int i=0; i<myProductArray.length; i++){
String temp = template.replace("productId",myProductArray[i]);
temp = temp.replace("productName",myNameArray[i]);
if(result.length() > 1)
result.append(",");
result.append(temp);
}
result.append("]");
return result.toString();
If you can replace the template String with a StringBuffer and manipulate that directly, it'll make a ton of difference performance wise for large Strings.
Regards,
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.