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"}
Related
I have following JSONObject (not array, which I don't mind to convert). I am trying to do two things:
get the count of genre entry as "poetry" (count = 2).
get the key value of author name and genre:
authorName = malcolm
genreName = newsarticle
authorName = keats
genreName = poetry
{ "AddressBook" :{
"Details" :{
"authorname" :{
"Author-malcolm":{
"genre" :"poetry"
}
"Author-keats":{
"genre" :"poetry"
}
}
}
}
}
Code which I tried:
public static void main(String[] args) throws Exception, IOException, ParseException {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("My path to JSON"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray arrayhere = new JSONArray();
arrayhere.add(obj);
System.out.println(arrayhere);
int count = 0;
for(int i = 0; i < arrayhere.size(); i++) {
JSONObject element = arrayhere.getJSONObject(i);//The method getJSONObject(int) is undefined for the type JSONArray
String branchName = element.getString("genre");//The method getString(String) is undefined for the type JSONObject
if(branchName.equals("poetry")) {
count ++;
}
}
System.out.println("Count f0r poetry genre=" + count);
}
}
I have looked at solutions all over. There is no question similar to this at stackoverflow. I am not sure if the procedure is correct.
A few problems here.
First, I'm not sure where you got that example JSON but you can't work with that. That's not even valid JSON Formatting.
Looks like you want something like this:
{
AddressBook:
[
{
authorname: "author-malcom",
genre:"poetry"
},
{
authorname: "author-keats",
genre: "poetry"
}
]
}
That's the structure you're trying to create in JSON.
So, you're parsing this in from a file into a JSONObject that has a key called AddressBook inside of it. That key points to an array of JSONObjects representing authors. Each of those objects will have a key called genre. You're trying to access the genre key and count on a condition.
What you did above was create attempt to create a JSONObject from an invalid string, and then add the entire JSONObject itself into the JSONArray. JSONArray.add() doesn't convert an object to an array, it literally adds it onto the array.
jsonObj => {"Name":"name1","Id":1000}
jsonArray.add(jsonObj)
jsonArray => [{"Name":"name1","Id":1000}]
That's what you did in your code above. You didn't create an array from a JSONObject, you added an object to the array.
Proper use is going to look like:
Object obj = parser.parse(new FileReader("path_to_file"));
JSONObject jobj = (JSONObject) obj;
//access key AddressBook
JSONArray author_array = jobj.getJSONArray("AddressBook");
int poetry = 0;
for(int i = 0; i < author_array.length(); i++) {
JSONObject author = (JSONObject) author_array.get(i);
if(author.getString("genre").equals("poetry")) {
poetry++;
}
}
To summarize, you're problems come from a lack of understanding about JSON Formatting and how to access elements within a JSON Object.
Paste in the sample JSONObject I gave you above here. That site will let you visualize what you're working with.
I'm reading the JSONObject as input and i am retrieving the value of key "id" using getString() method of net.sf.json API but i'm curious to know why it is not going in the if block..
INPUT:
{
"id" : null
}
code:
//reading the jsonObject from String
JSONObject jsonObject.fromObject(someString);
String id = jsonObject.getString("id");
if( id == null)
{
//the control is not going in this if condition
}
use optString("id",null) after isNull() check when you not sure about JSON format will be same and to handle NPE.
JSONObject jO=jsonObject.fromObject(someString);
String id = jO.optString("id",null);
if(jO.isNull("id"))
{
//the control is not going in this if condition
}
else{
}
or
jsonObject.optJSONObjet(String arg1)
read this
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");
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
I have JSON object as follows:
member = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
In Java I want to parse the above json object and store the values in an arraylist.
I am seeking some code through which I can achieve this.
I'm assuming you want to store the interestKeys in a list.
Using the org.json library:
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}
public class JsonParsing {
public static Properties properties = null;
public static JSONObject jsonObject = null;
static {
properties = new Properties();
}
public static void main(String[] args) {
try {
JSONParser jsonParser = new JSONParser();
File file = new File("src/main/java/read.json");
Object object = jsonParser.parse(new FileReader(file));
jsonObject = (JSONObject) object;
parseJson(jsonObject);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void getArray(Object object2) throws ParseException {
JSONArray jsonArr = (JSONArray) object2;
for (int k = 0; k < jsonArr.size(); k++) {
if (jsonArr.get(k) instanceof JSONObject) {
parseJson((JSONObject) jsonArr.get(k));
} else {
System.out.println(jsonArr.get(k));
}
}
}
public static void parseJson(JSONObject jsonObject) throws ParseException {
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
if (jsonObject.get(obj) instanceof JSONArray) {
System.out.println(obj.toString());
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
parseJson((JSONObject) jsonObject.get(obj));
} else {
System.out.println(obj.toString() + "\t"
+ jsonObject.get(obj));
}
}
}
}}
Thank you so much to #Code in another answer. I can read any JSON file thanks to your code. Now, I'm trying to organize all the elements by levels, for could use them!
I was working with Android reading a JSON from an URL and the only I had to change was the lines
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
for
Iterator<?> iterator = jsonObject.keys();
I share my implementation, to help someone:
public void parseJson(JSONObject jsonObject) throws ParseException, JSONException {
Iterator<?> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String obj = iterator.next().toString();
if (jsonObject.get(obj) instanceof JSONArray) {
//Toast.makeText(MainActivity.this, "Objeto: JSONArray", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString());
TextView txtView = new TextView(this);
txtView.setText(obj.toString());
layoutIzq.addView(txtView);
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
//Toast.makeText(MainActivity.this, "Objeto: JSONObject", Toast.LENGTH_SHORT).show();
parseJson((JSONObject) jsonObject.get(obj));
} else {
//Toast.makeText(MainActivity.this, "Objeto: Value", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString() + "\t"+ jsonObject.get(obj));
TextView txtView = new TextView(this);
txtView.setText(obj.toString() + "\t"+ jsonObject.get(obj));
layoutIzq.addView(txtView);
}
}
}
}
1.) Create an arraylist of appropriate type, in this case i.e String
2.) Create a JSONObject while passing your string to JSONObject constructor as input
As JSONObject notation is represented by braces i.e {}
Where as JSONArray notation is represented by square brackets i.e []
3.) Retrieve JSONArray from JSONObject (created at 2nd step) using "interests" as index.
4.) Traverse JASONArray using loops upto the length of array provided by length() function
5.) Retrieve your JSONObjects from JSONArray using getJSONObject(index) function
6.) Fetch the data from JSONObject using index '"interestKey"'.
Note : JSON parsing uses the escape sequence for special nested characters if the json response (usually from other JSON response APIs) contains quotes (") like this
`"{"key":"value"}"`
should be like this
`"{\"key\":\"value\"}"`
so you can use JSONParser to achieve escaped sequence format for safety as
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(inputString);
Code :
JSONParser parser = new JSONParser();
String response = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
JSONObject jsonObj = (JSONObject) parser.parse(response);
or
JSONObject jsonObj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> interestList = new ArrayList<String>();
JSONArray jsonArray = jsonObj.getJSONArray("interests");
for(int i = 0 ; i < jsonArray.length() ; i++){
interestList.add(jsonArray.getJSONObject(i).optString("interestKey"));
}
Note : Sometime you may see some exceptions when the values are not available in appropriate type or is there is no mapping key so in those cases when you are not sure about the presence of value so use optString, optInt, optBoolean etc which will simply return the default value if it is not present and even try to convert value to int if it is of string type and vice-versa so Simply No null or NumberFormat exceptions at all in case of missing key or value
From docs
Get an optional string associated with a key. It returns the
defaultValue if there is no such key.
public String optString(String key, String defaultValue) {
String missingKeyValue = json_data.optString("status","N/A");
// note there is no such key as "status" in response
// will return "N/A" if no key found
or To get empty string i.e "" if no key found then simply use
String missingKeyValue = json_data.optString("status");
// will return "" if no key found where "" is an empty string
Further reference to study
How to convert String to JSONObject in Java
Convert one array list item into multiple Items
There are many JSON libraries available in Java.
The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.
There are typically three things one should look at for choosing any library:
Performance
Ease of use (code is simple to write and legible) - that goes with features.
For mobile apps: dependency/jar size
Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.
For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs.
For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...
Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.
For your particular example, the following code decodes your json with jackson:
public class MyObj {
private List<Interest> interests;
static final class Interest {
private String interestKey;
}
private static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws IOException {
MyObj o = JACKSON.readValue("{\"interests\": [{\"interestKey\": \"Dogs\"}, {\"interestKey\": \"Cats\" }]}", MyObj.class);
}
}
Let me know if you have any questions.
Trying to parse multi-level JSON in Java.
Having JSON input in format like this:
{"object1":["0","1", ..., "n"],
"objects2":{
"x1":{"name":"y1","type":"z1","values":[19,20,21,22,23,24]}
"x2":{"name":"y2","type":"z2","values":[19,20,21,22,23,24]}
"x3":{"name":"y3","type":"z1","values":[19,20,21,22,23,24]}
"x4":{"name":"y4","type":"z2","values":[19,20,21,22,23,24]}
}
and need to get all objects from 2 by one of the attributes, e.g. get all objects with type = z1.
Using org.json*.
Tried to do something like this:
JSONObject GeneralSettings = new JSONObject(sb.toString()); //receiving and converting JSON;
JSONObject GeneralObjects = GeneralSettings.getJSONObject("objects2");
JSONObject p2;
JSONArray ObjectsAll = new JSONArray();
ObjectsAll = GeneralObjects.toJSONArray(GeneralObjects.names());
for (int i=0; i < GeneralObjects.length(); i++){
p2 = ObjectsAll.getJSONObject(i);
switch (p2.getString("type")) {
case "z1": NewJSONArray1.put(p2); //JSON array that should contain values with type z1.
break;
case "z2": NewJSONArray2.put(p2); //JSON array that should contain values with type z2.
default: System.out.println("error");
break;
}
}
}
But getting null pointer exception and overall method seems not to be so well.
Please advise, is there any way to make it easier or, what am I doing wrong?
If you're getting a NullPointerException it's most likely that you haven't initialized NewJSONArray1 and NewJSONArray2.
You didn't include their declaration, but you probably just need to do
NewJSONArray1=new JSONArray();
NewJSONArray2=new JSONArray();
before your loop.
Aside: by convention java variables should start with a lower case letter, e.g. newJSONArray1
public static void main(String[] args) {
String s =
"{\"object1\":[\"0\",\"1\",\"n\"]," +
"\"objects2\":{" +
"\"x1\":{\"name\":\"y1\",\"type\":\"z1\",\"values\":[19,20,21,22,23,24]}," +
"\"x2\":{\"name\":\"y2\",\"type\":\"z2\",\"values\":[19,20,21,22,23,24]}," +
"\"x3\":{\"name\":\"y3\",\"type\":\"z1\",\"values\":[19,20,21,22,23,24]}," +
"\"x4\":{\"name\":\"y4\",\"type\":\"z2\",\"values\":[19,20,21,22,23,24]}" +
"}}";
System.out.println(s);
JSONObject json = new JSONObject(s);
JSONObject object2 = json.optJSONObject("objects2");
if (object2 == null) {
return;
}
JSONArray result = new JSONArray();
for (Object key : object2.keySet()) {
JSONObject object = object2.getJSONObject(key.toString());
String type = object.optString("type");
if ("z1".equals(type)) {
System.out.println(object.toString());
result.put(object);
}
}
System.out.println(result);
}
You can always convert it to string and use json-path:
https://code.google.com/p/json-path/