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");
Related
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
I have simple json which looks like this :
[
{
"id":"0",
"name":"Bob",
"place":"Colorado",
},
{
"id":"1",
"name":"John",
"place":"Chicago",
},
{
"id":"2",
"name":"Marry",
"place":"Miami",
}
]
What I want is using Java to create list of strings (List<String>) that contains all 'names'. I have some experience using Gson and I think about something like:
Gson gson = new Gson();
String[] stringArray= gson.fromJson(jsonString, " ".class);
The problem with this method is that I should create some POJO class which I didn`t in this case. Is it any way I can achieve it without creating separate class with this 'name' property ?
Using Jackson to parse, and Java 8 Streams API for extracting only the name field; the following may help you:
// Your string
jsonString = "[{ \"id\":\"0\", \"name\":\"Bob\", \"place\":\"Colorado\" }, { \"id\":\"1\", \"name\":\"John\", \"place\":\"Chicago\"}, { \"id\":\"2\", \"name\":\"Marry\", \"place\":\"Miami\" }]";
// using Jackson to parse
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getTypeFactory();
List<MyInfo> myObjectList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, MyInfo.class));
// Java 8 Collections
List<String> nameList = myObjectList.stream().map(MyInfo::getName).collect(Collectors.toList());
Beware, it implies the usage of a MyInfo class representing your a Java class in which Json objects of yours would fit in.
You can use JSONArray to get value from key 'name'. Like this:
JSONArray jSONArray = new JSONArray(yourJson);
List<String> list = new ArrayList<>();
for (int i = 0; i < jSONArray.length(); i++) {
JSONObject object = (JSONObject) jSONArray.get(i);
String value = object.getString("name");
System.out.println(value);
list.add(value);
}
You may try the following code snippet,
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
List<String> ls = new ArrayList<String>();
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONParser jsonParse = new JSONParser();
String str = "[{\"id\": \"0\",\"name\": \"Bob\",\"place\": \"Colorado\"},"
+ "{\"id\": \"1\",\"name\": \"John\",\"place\": \"Chicago\"},"
+ "{\"id\": \"2\",\"name\": \"Marry\",\"place\": \"Miami\"}]";
try {
jsonArr= (JSONArray) jsonParse.parse(str); //parsing the JSONArray
if(jsonArr!=null){
int arrayLength =jsonArr.size(); //size is 3 here
for(int i=0;i<arrayLength;i++){
jsonObj = (JSONObject) jsonParse.parse(jsonArr.get(i).toString());
ls.add(jsonObj.get("name").toString()); //as we need only value of name into the list
}
System.out.println(ls);
}
} catch (ParseException e) {
e.printStackTrace();
}catch(Exception e1){
e1.printStackTrace();
}
As you have array, use JSONArray and used jsonParse to avoid any parsing error.
I have used json-simple API to acheive the above.
Is there a way to just one field from the JSON string? My code is as follows:
Object obj = parser.parse(resp);
System.out.println(obj);
JSONArray array = new JSONArray();
array.add(obj);
JSONObject obj2 = (JSONObject)array.get(0); //Getting NPE here
//Object obj3 = obj2.get("data");
System.out.println("Data: " + obj2.get("data"));
//System.out.println("Email: " + obj3.get("email_address"));
I'm using the following libraries
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
From the response string resp, I just need data.email_address. I am unable to find a way to do it.
So if this is your input:
{
"data": {
"email_address": "example#example.com"
}
}
You first will need to make it a JSONObject:
JSONObject object = (JSONObject) new JSONParser().parse(json);
And then you can get data, another JSONObject:
JSONObject data = (JSONObject) object.get("data")
And from your data Object you can get email_address:
String email = data.get("email_address").toString();
If your input is an array of users, like this:
{
"users": [
{
"data": {
"email_address": "example#example.com"
}
},
{
"data": {
"email_address": "exapmle2#example2.com"
}
}
]
}
You can get it the same way:
JSONObject object = (JSONObject) new JSONParser().parse(json);
JSONArray users = (JSONArray) object.get("users");
JSONObject user0 = (JSONObject) users.get(0);
JSONObject user0data = (JSONObject) user0.get("data");
String email = user0data.get("email_address").toString();
First parse the whole JSON into an Object. Then get an array called users, from that array, get index 0. From that Object, get data, and then email_address
The other option is to use jsonpath.
Using the same Json blob as Lorant:
{
"data": {
"email_address": "example#example.com"
}
}
You would use the following expression.
$.data.email_address
Or if it was an array, simply.
$.users.[data].email_address
An online tool can be used to experiment and learn the syntax, but if you know xpath it should be somewhat familiar already.
import org.json.JSONObject;
JSONObject json = new JSONObject(record);
json.getString("fieldName"));
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"}
I want to use financial data from yahoo in my program, it already works. I get the complete JSON content and I can display it. But now I want to extract the price as int.
public class Main {
public static void main (String[]args) throws IOException {
String sURL = "http://finance.yahoo.com/webservice/v1/symbols/googl/quote?format=json"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
System.out.print(rootobj);
}
}
EDIT
This is the JSON data from yahoo
{
"list" : {
"meta" : {
"type" : "resource-list",
"start" : 0,
"count" : 1
},
"resources" : [
{
"resource" : {
"classname" : "Quote",
"fields" : {
"name" : "Google Inc.",
"price" : "554.520020",
"symbol" : "GOOGL",
"ts" : "1432324800",
"type" : "equity",
"utctime" : "2015-05-22T20:00:00+0000",
"volume" : "1213288"
}
}
}
]
}
}
EDIT 2
I changed my code
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject obj = root.getAsJsonObject();
JsonObject result = obj.get("list").getAsJsonObject();
String result2 = result.get("resources").toString();
System.out.print(result2);
And now I already get this
[{"resource":{"classname":"Quote","fields":{"name":"Google Inc.","price":"554.520020","symbol":"GOOGL","ts":"1432324800","type":"equity","utctime":"2015-05-22T20:00:00+0000","volume":"1213288"}}}]
How can I get the "price" now?
EDIT 3
Ok I got it now, it works and I only get the price as double, but is this a smart way to solve this task?
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject obj = root.getAsJsonObject();
JsonObject result = obj.get("list").getAsJsonObject();
JsonArray result2 = result.get("resources").getAsJsonArray();
JsonObject result3 = result2.get(0).getAsJsonObject();
JsonObject result4 = result3.get("resource").getAsJsonObject();
JsonObject result5 = result4.get("fields").getAsJsonObject();
String result6 = result5.get("price").toString();
result6 = result6.replace("\"", "");
double value = Double.parseDouble(result6);
System.out.print(value);
you should reach "fields" object to extract "name", "price" etc.
The org.json library is easy to use. Example code below: your response as a string :
JSONObject obj1 = new JSONObject(response);
JSONArray arr = obj1.getJSONObject("list").getJSONArray("resources"); //GETS RESOURCES ARRAY
for (int i = 0; i < arr.length(); i++)
{
String resource = arr.getJSONObject(i).toString();
JSONObject obj2 = new JSONObject(resource);
String resourceObject = obj2.getJSONObject("resource").toString(); //RESOURCE OBJECT
JSONObject obj3 = new JSONObject(resourceObject);
String name = obj3.getJSONObject("fields").getString("name"); //REACHED THE FIELDS
float price = (float)obj3.getJSONObject("fields").getDouble("price");
System.out.println(name);
System.out.println(price);
}
Download : http://mvnrepository.com/artifact/org.json/json
He is already using gson.
If you want to continue using gson and know the structure before, you could create classes that stores the data.
class GoogleRequest{
private GoogleList list;
public GoogleList getList() {
return list;
}
public void setList(GoogleList list) {
this.list = list;
}
}
// class for list
class GoogleList{
private Meta meta;
private List<Resources> resources;
public List<Resources> getResources() {
return resources;
}
public void setResources(List<Resources> resources) {
this.resources = resources;
}
public Meta getMeta() {
return meta;
}
public void setMeta(Meta meta) {
this.meta = meta;
}
}
// create other classes here like the Resources class
JsonParser jp = new JsonParser(); // from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream)request.getContent()));
GoogleRequest list = new Gson().fromJson(root,GoogleRequest.class);
The GoogleRequest should hold a List object and a Meta object. gson will introspect and set the properties. gson will set properties to null if they where not introspected. So you could use.
if( list.getResources() != null ){
// list is here
}else{
// do some other code and parse diffrent json
}
If you don't know if it is a array or object create different classes to handle it for you. Just parse the data with new Gson().fromJson();
Now remember that you need right properties for the job. Let's say you have this json in java
String json = "{\"price\" : \"554.520020\"}";
Then price needs to be Double or double. If you use Double you could check
if( obj.getPrice() != null ){
System.out.println( obj.getPrice().intValue() );
}
Note: you will loose precision if you cast double to int