Issue with converting string to json in Java - java

I'm new in Java and I'm creating a web app using Servlet in Eclipse.
I want to convert string to JSON using this code :
import org.json.JSONException;
import org.json.JSONObject;
JSONObject jsonObject = null;
jsonObject = new JSONObject(STRING);
System.out.println(jsonObject.getString("PROPERTY_NAME"));
It works fine if STRING be equal to "{'status':0}" and jsonObject.getString("status") gives me 0.
But I get a response from API like "{"status":0}" and jsonObject.getString("status") gives me error because jsonObject is :
{}
And the error is :
org.json.JSONException: JSONObject["status"] not found.
Do you have any solution about this?

Problem is with the value not key. i've tested this, it works
JSONObject jsonObject = null;
jsonObject = new JSONObject("{\"status\":0}");
System.out.println(jsonObject.getInt("status"));
or this
JSONObject jsonObject = null;
jsonObject = new JSONObject("{\"status\":'0'}");
System.out.println(jsonObject.getString("status"));

You need to escape your double quotes in your STRING variable:
"{\"status\":0}"
You can do that programmatically like that (we need to call toString() because STRING is an instance of StringBuilder):
String escapedJsonStr = STRING.toString().replaceAll("\"", "\\\"");

I can help you with below example...
for (String key: jsonObject.keySet()){
System.out.println(key); }
This will fetch you the set of Keys in the JSON.
JSONObject json_array = args.optJSONObject(0);
Iterator keys = json_array.keys();
while( keys.hasNext() ) {
String key = (String) keys.next();
System.out.println("Key: " + key);
System.out.println("Value: " + json_array.get(key)); }
I recommend following the link for a thorough understanding of Java and JSON -- Example

Related

JSON parsing error in java using simle json parser

Let I have a string, json string.
{"cond":{"to_email":"b#b.c"},"ret":"all"}
Now I want to parse it using json simple parser in java.
I am giving the code...
try{
//String s=request.getParameter("data");
String s="{\"cond\":{\"to_email\":\"b#b.c\"},\"ret\":\"all\"}";
JSONParser jsp=new JSONParser();
if(s == null || s.equals("")){
//problem
String json="{\"error\":\"error\",\"message\":\"no json data\"}";
response.getWriter().println(json);
}else{
JSONObject obj=(JSONObject) jsp.parse(s); //only object is allowed
JSONObject condObj=(JSONObject) jsp.parse(""+obj.get("cond"));
JSONObject returnObj=(JSONObject) jsp.parse(""+obj.get("ret"));
System.out.println(condObj);
}
Now the problem is that it's giving error...
Unexpected character (a) at position 0.
But if I remove the "ret" : "all" then it's working well.
Here in the example I printed condObj only but if I print retObj then it's giving null. So, the problem is the the "ret" : "all" part...
But it's a correct json. I checked it. How to get out of this problem??
The thing is very simple!
The key "cond" represents an complex JSONObject but the key "ret" just a String. So the parsing fails in this case. I dont know which JSON-libary you are using, but have a look for an JSONObject#getString(String key) method to get the value.
Good luck
UPDATE (with the JSON lib I use)
try{
//String s=request.getParameter("data");
String s="{\"cond\":{\"to_email\":\"b#b.c\"},\"ret\":\"all\"}";
if(s == null || s.equals("")){
//problem
String json="{\"error\":\"error\",\"message\":\"no json data\"}";
}else{
JSONObject obj= new JSONObject(s);
JSONObject condObj=(JSONObject) obj.getJSONObject("cond");
String returnObj= obj.getString("ret");
System.out.println(condObj);
System.out.println(returnObj);
}
}
catch (Exception e) {
e.printStackTrace();
}
Just following the above answer ,here is a simple parser.
import java.util.Set;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class ParseJson {
public static void main(String[] args) throws Exception {
String s = "{\"cond\":{\"to_email\":\"b#b.c\"},\"ret\":\"all\"}";
JSONParser jsp = new JSONParser();
if (s == null || s.equals("")) {
String json = "{\"error\":\"error\",\"message\":\"no json data\"}";
} else {
JSONObject obj = (JSONObject) jsp.parse(s);
JSONObject condObj = (JSONObject) jsp.parse("" + obj.get("cond"));
Set<String> keys = obj.keySet();
for (String key : keys) {
System.out.println("Key : " + key);
System.out.print("Value : " +obj.get(key));
System.out.println();
}
}
}
}
This prints both the key and value pairs for you. We can add conditionals for specific keys.
Key : ret
Value : all
Key : cond
Value : {"to_email":"b#b.c"}

Hi, I need help parse through a JSON file in Java

I am trying to parse through a JSON file using the library JSON simple. The first two string are good. However, when I try to parse through object social I get facebook: null, Pinterest : null, and rss: null. How do I parse through my second object?
Here is my JSON file
{
"blogURL": "www.sheriyBegin",
"twitter": "http://twitter.com/Sherily",
"social": {
"facebook": "http://facebook.com/Sherily",
"pinterest": "https://www.pinterest.com/Sherily/Sherily-articles",
"rss": "http://feeds.feedburner.com/Sherily"
}
}
Here is the code I wrote
package javaugh;
import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JavaUgh {
public static void main(String[] args)throws Exception{
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("C:\\Users\\HP\\Desktop\\Research\\file2.txt"));
JSONObject jsonObject = (JSONObject) obj;
String blog = (String)jsonObject.get("blogURL");
String twitter = (String)jsonObject.get("twitter");
JSONObject jsonObject2 = (JSONObject) obj;
String face = (String)jsonObject2.get("facebook");
String pin = (String)jsonObject2.get("pinterest");
String rss = (String)jsonObject2.get("rss");
System.out.println("Blog: "+ blog);
System.out.println("Twitter Page : " + twitter);
System.out.println("Socail:");
System.out.println("Facebook Page : " + face);
System.out.println("Pintersect: " + pin);
System.out.println("Rss : " + rss);
}
}
Output:
Blog: www.sheriyBegin
Twitter Page : http://twitter.com/Sherily
Socail:
Facebook Page : null
Pintersect: null
Rss : null
You should obtain the second json object from the first one, not by creating a new reference to the first one.
JSONObject jsonObject2 = (JSONObject) jsonObject.get("social");
JSONObject social = (JSONObject) jsonObject.get("social");
String face = (String)social.get("facebook");
String pin = (String)social.get("pinterest");
String rss = (String)social.get("rss");

JSONObject not workign

I am building an app for android.
I fire and HTTP GET request and this request returns a JSONObject. I want to retrieve the value by key. But this is not working properly.
This is the JSONObject named obj that I receive:
{"id":1,"name":"math","description":"This is a math course."}
If I log Log.d("title", String.valueOf(obj.has("name"))); this will result into true.
This works for all keys in the JSONObject.
But if I want to receive the name and do this so:
Log.d("title", obj.getString("name"));
I will get an unhandled exception: org.json.JSONException.
Does anybody know how I can fix this problem?
Maybe you should try someting like this:
Log.d("title", obj.name);
var obj = $.parseJSON('{"id":1,"name":"math","description":"This is a math course."}');
alert(obj['name']);
Try this :) You can use JSON.parse insted of $.parseJSON if you are not using jquery. Following in Java
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
Everything between the { } makes part of an array, so you first need to get a JSONArray like this:
JSONArray myJSONArray = obj.getJSONArray();
And then you can access the field values with:
myJSONArray.getString("name") etc...
Search on google how to work with JSONArray.

How to decode json without knowing the key/name string?

I am receiving a json string in the following format:
{"27":{"id":"27","uid":"4","title":"teamer.zapto.org","url":"www.google.jo","ip":"74.125.234.63","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058071"}},"fetch_interval":"60","ping_shift":"0"},
"30":{"id":"30","uid":"4","title":"google","url":"www.google.com","ip":"74.125.234.114","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058079"}},"fetch_interval":"60","ping_shift":"0"},
"31":{"id":"31","uid":"4","title":"facebook.com","url":"facebook.com","ip":"69.171.247.21","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058095"}},"fetch_interval":"60","ping_shift":"0"},
"32":{"id":"32","uid":"4","title":"ebir","url":"www.ebir.com","ip":"74.52.50.226","enabled":"1","services":{"Ftp":{"status":"1","ts":"1355058073"},"Http 1":{"status":"1","ts":"1355058073"}},"fetch_interval":"60","ping_shift":"0"},
"33":{"id":"33","uid":"4","title":"zapto","url":"teamer.zapto.org","ip":"200.35.150.6","enabled":"1","services":{"Http 1":{"status":"0","ts":"1355056146"}},"fetch_interval":"3600","ping_shift":"2"},
"35":{"id":"35","uid":"4","title":"vogella.com","url":"vogella.com","ip":"46.163.79.226","enabled":"1","services":{"Ftp":{"status":"1","ts":"1355058098"},"Http 1":{"status":"1","ts":"1355058098"}},"fetch_interval":"60","ping_shift":"0"},
"36":{"id":"36","uid":"4","title":"msn","url":"www.msn.com","ip":"131.253.13.140","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058103"}},"fetch_interval":"60","ping_shift":"0"},
"37":{"id":"37","uid":"4","title":"dubizzle.com","url":"www.dubizzle.com","ip":"94.236.93.152","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058068"}},"fetch_interval":"60","ping_shift":"0"},
"38":{"id":"38","uid":"4","title":"olx.jo","url":"olx.jo","ip":"204.74.99.100","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058108"}},"fetch_interval":"60","ping_shift":"0"},
"40":{"id":"40","uid":"4","title":"www.sukar.com","url":"www.sukar.com","ip":"72.52.8.195","enabled":"1","services":{"Ftp":{"status":"0","ts":"1355058092"},"Http 1":{"status":"1","ts":"1355058092"}},"fetch_interval":"60","ping_shift":"0"}}
as you can see the keys are numbers (27, 30, 31,...) and are not consecutive. How can I get the data from such json? I know that it must be some kind of loop depending on length but I couldn't figure it out on how to do so. Usually I'd use jObject.getString("id"), but since I don't know what the string would be what can I do?
If you have a JSONObject as the root, you should be able to do the following:
JSONObject root = new JSONObject(jsonString);
JSONArray names = root.names();
for(int i = 0; i < names.length(); i++) {
String tag = names.getString(i);
...
}
The tag will be the numeric tag you refer to.
JSONObject questionMark = new JSONObject(jsonString);
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);

Parse JSON object with string and value only

I have problem when trying to parse with minimum value to map in Android.
There some sample JSON format with more information ex:
[{id:"1", name:"sql"},{id:"2",name:"android"},{id:"3",name:"mvc"}]
This that example most common to use and easy to use just use getString("id") or getValue("name").
But how do I parse to map using this JSON format with just only string and value minimum format to java map collection using looping. And because the string json will always different one with another. ex:
{"1":"sql", "2":"android", "3":"mvc"}
Thank
You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
My pseudocode example will be as follows:
JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();
for (each json in jsonArray) {
String id = json.get("id");
String name = json.get("name");
newJson.put(id, name);
}
return newJson;

Categories

Resources