Retrieve the JSON Object - java

Below I have attached Java code, In that first i am retrieving the "images" result as "{"jpg":"JPEG file","gif":"GIF file","png":"PNG File"}"
using the resultant, trying to get the "jpg" node, not able to retrieve the data, instead i am getting error as java.lang.String cannot be cast to org.json.simple.JSONObject
I like to take the images and followed by jpg. not directly JPG value
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JSONDemo {
public static void main(String[] args) {
try{
String jsonfile="{ \"name\" : \"Raj\", \"Address\" : \"Chennai\", \"images\": { \"jpg\" : \"JPEG file\", \"png\" : \"PNG File\", \"gif\" : \"GIF file\" }}";
JSONObject jobject=new JSONObject();
JSONParser jparser=new JSONParser();
jobject = (JSONObject) jparser.parse(jsonfile);
jobject=(JSONObject) jobject.get("images");
System.out.println(jobject);
System.out.println(jobject.getClass().getName());
jobject=(JSONObject) jobject.get("jpg");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}

Your error here is that "jpg" is not a JSONObject, but a key with the associated value "JPEG file" which is a simple String. That is why you're getting such error.
In ordre to retrieve the value associated to the key jpg, read the below code. I added some comments to help you understand each steps, but feel free to ask for more details.
String jsonfile="{ \"name\" : \"Raj\", \"Address\" : \"Chennai\", \"images\": { \"jpg\" : \"JPEG file\", \"png\" : \"PNG File\", \"gif\" : \"GIF file\" }}";
JSONObject jobject = new JSONObject();
JSONParser jparser = new JSONParser();
//Convert your string jsonfile into a JSONObject
try {
jobject = (JSONObject) jparser.parse(jsonfile);
} catch (ParseException ex) {
Logger.getLogger(Josimarleewords.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(jobject.toString());
//{"Address":"Chennai","name":"Raj","images":{"jpg":"JPEG file","png":"PNG File","gif":"GIF file"}}
//Get the node image, and convert it into a JSONObject
//You're able to do so, because the value associated to "images"
//is in json format.
jobject=(JSONObject) jobject.get("images");
System.out.println(jobject.toString());
//{"jpg":"JPEG file","png":"PNG File","gif":"GIF file"}
//Retrieves the value associated to the key jpg.
//The value here is not in json format, it is a simple string
String jpg = (String)jobject.get("jpg");
System.out.println(jpg.toString());
//JPEG file

Related

How to load JSON from string path in Java and print the json values?

I would like to print all the json objects that are in a particular json file.
My function receive a string that is the path of a json within my project. movieListJSON is the path of my json.
This is my folder structure:
templates
*fetchIMDB.java
*Movie.class
movies.json
That is what i tried so far, but I dont find a way to open the json and iterate through the values by the key.
public void fetchIMDBMovies(String movieListJSON, String outputDir) throws IOException {
//
JSONObject jsonObject;
System.out.println(movieListJSON);
JSONParser parser = new JSONParser();
InputStream in = getClass().getResourceAsStream(movieListJSON);
}
My json file looks like:
[
{
"movie_name": "Avatar"
},
{
"movie_name": "Star Wars VII: The Force Awakens"
},
{
"movie_name": "Pirates of the Caribbean: At World's End"
},
{
"movie_name": "Spectre"
},
{
"movie_name": "The Dark Knight Rises"
}
]
How can I get all the json with value movie_name and print them all using System.out.println();
I want to print the movie names (value of the movie_name in json)
Here is the solution.
Instead of 'your-path' enter the path to your file. If you use Intelij Idea, you can get it by Right click on file + Copy path... + Copy relative path (or full path, as you want)
try {
JSONArray array = (JSONArray) new JSONParser().parse(new FileReader("your-path"));
for (Object temp : array) {
JSONObject jsonObject = (JSONObject) temp;
System.out.println(jsonObject.get("movie_name"));
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}

Cannot cast from JsonElement to String while parsing from the JSON file

This is my first code for reading from a Json file but I keep getting an error message:
Can not cast from JasonElement to String
import java.io.FileReader;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Json
{
public static void main(String args[])
{
JsonParser parser = new JsonParser();
try
{
Object obj = parser.parse(new FileReader("C:\\Users\\dell\\eclipse-
workspace\\Assignment\\data.json"));
JsonObject jsonObject = (JsonObject) obj;
String name = (String) jsonObject.get("Name");
String author = (String) jsonObject.get("Author");
System.out.println("Name: " + name);
System.out.println("Author: " + author);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Excuse me for any silly mistakes.
I am still a beginner
By involking jsonObject.get("Name") you will get a JsonElement object and you can not cast to String. Maybe you can try:
jsonObject.get("Name").toString();
It depends on what you want.
If Name needs to be an actual JSON string value (as in, it must be { "Name": "str" } and not { "Name": [] }), then you should say jsonObject.get("Name").getAsString(). This causes an error if it isn't a string, which is desirable.
Otherwise, use jsonObject.get("Name").toString(), which returns a valid JSON value, as a String. E.g.
{ "Name": "a" } -> "a" (That's a string, 3 characters, two quote marks and an 'a')
{ "Name": false } -> false (That's a string, 5 chars, no quotes)

Parse.com add JSON Object to JSON Array

My problem is simple, I'd like to add a JSONObject to a JSONArray that I store in a MongoDB database. I can easily add all types of data like Strings, Ints etc but not JSONObjects.
I do this in my code :
public void done(ParseObject lan, ParseException e) {
if(e==null){
JSONObject object = new JSONObject();
try{
object.put("PlayerName","John");
object.put("ID",514145);
lan.add("Participants",object); //nothing gets inserted
lan.add("Participants",15); //works fine
lan.add("Participants",JSONObject.null); //works fine too
}catch (JSONException error){
}
lan.increment("Number");
lan.saveInBackground();
}else{
Log.i("Parse Error","error");
}
}
But nothing appears in my db and there's no error thrown.
Do you guys have any clue on how to do that ?
Try using object.toString() instead of object.
lan.add("Participants", object.toString());
JSON:
{"Participants":["{\"PlayerName\":\"John\",\"ID\":514145}"]}
To parse this JSON try this:
JSONObject jsonObj = new JSONObject(YOUR_JSON_STRING);
// Participants
JSONArray participantsJsonArray = jsonObj.getJSONArray("Participants");
// Participant
JSONObject participanJsonObject = participantsJsonArray.getJSONObject(0);
// PlayerName
String playerName = participanJsonObject.getString("PlayerName");
// ID
String id = participanJsonObject.getInt("ID");
Hope this will help~
Convert that Json Object into String and store it in string format
lan.add("Participants",object.toString());
And when you want to use that you can easily convert it into Json Object again like this
JSONObject jObj=new JSONObject("Your Json String");

Parse Json In Java How to read Inner Value

Very New with Java Development Parsing JSON in JAVA Here is my Code.
package com.zenga.control;
import java.io.BufferedReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class Start {
public String readUrl(String urlString) {
String jsonString = null;
try {
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(urlString);
client.executeMethod(get);
jsonString = get.getResponseBodyAsString();
}catch(Exception e) {
}
return jsonString;
}
public void getAddAsBeanObject() {
try {
String jsonString = new Start().readUrl("http://myDomain/JsonZ.json");
JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString);
System.out.println(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Start().getAddAsBeanObject();
}
}
As I successfully Read Value in JSONObject and it also showing all JSON String on console But How can i Get Value For ID and UID and DURATION ?
Here The JSONString the i read in System.out.println(obj);
{
"Demo": {
"CONTENT": [
{
"ID": " 283 ",
"UID": " 87897bc8-ae9b-11e1-bdcf-123141042154 ",
"DURATION": "Full"
},
{
"ID": " 283 ",
"UID": " 87897bc8-ae9b-11e1-bdcf-123141042154 ",
"DURATION": "Full"
}
]
}
}
Following code can be used to iterate the JSON objects inside the JSON array 'CONTENT', using .get(java.lang.String) as documented, to pull the value out of the JSONObject.
I have only demonstrated how to get the ID but the same logic applies to the other values.
JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString);
JSONArray content = obj.getJSONObject("Demo").getJSONArray("CONTENT");
java.util.Iterator<?> iterator = content.iterator();
while (iterator.hasNext()) {
JSONObject o = (JSONObject) iterator.next();
System.out.println(o);
System.out.println(o.get("ID"));
// etc...
}
Following is a sample code to reach the array`s inner objects specific to pattern you have provided.
String str = "{"+
"\"Demo\": {"+
"\"CONTENT\": ["+
" {"+
"\"ID\": \" 283 \","+
"\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+
"\"DURATION\": \"Full\""+
" },"+
"{"+
"\"ID\": \" 283 \","+
"\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+
"\"DURATION\": \"Full\""+
" }"+
"]"+
"}"+
"}";
try {
JSONObject jsr = new JSONObject(str); // JSON object with above data
JSONObject demo = jsr.getJSONObject("Demo"); // get Demo which is a JSON object inside jsr.
JSONArray content = demo.getJSONArray("CONTENT");// get CONTENT which is Json array inside Demo
for (int i = 0; i < content.length(); i++) { // iterate over array to get inner JSON objects and extract values inside
JSONObject record = content.getJSONObject(i); // each item of Array is a JSON object
String ID = record.getString("ID");
String UID = record.getString("UID");
String DURATION = record.getString("DURATION");
}
}
catch (JSONException e) {
e.printStackTrace();
}
Note: Above code is specifc to org.Json API. Find appropriate methods in library you are using for Json handling
Use a loop that iterates through the Json Object and access each of the element
for(/**loop until the counter reaches the size of the json object**/) {
//Access each element based on the ID as below.
System.out.println(Demo.CONTENT[CurrentCounter].ID); //here CurrentCounter is index
System.out.println(Demo.CONTENT[CurrentCounter].UID); ..... //read through all ids
}
I guess you could use the 'get' Method on the JSONObject. If you don't know which key to look for, I suggest using a Method that returns all available keys, like the one called 'keys'. With these values, you could then traverse down in you structure. See here:
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html
I guess GSON will be a big help for you.
See here Parsing json object into a string
There is a samplecode as well
Create a class which have variables you want to read from json string.And Gson will handle the rest.
https://code.google.com/p/google-gson/
Example usage:
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);

How to get specific JSON data?

Hi I am trying to read JSON from an ReST API but Im getting a nullpointer exception because mycode is not correct.
I have a JSON that I am reading from looking like this :
processJSON({
"LocationList":{
"noNamespaceSchemaLocation":"http://api.vasttrafik.se/v1/hafasRestLocation.xsd",
"servertime":"16:13",
"serverdate":"2013-03-22",
"StopLocation":[{
"name":"Brunnsparken, Göteborg",
"lon":"11.967824",
"lat":"57.706944",
"id":"9021014001760000",
"idx":"1"
},{
"name":"Brunnsgatan, Göteborg",
"lon":"11.959455",
"lat":"57.693766",
"id":"9021014001745000",
"idx":"4"
},{
"name":"Brunnslyckan, Lerum",
"lon":"12.410219",
"lat":"57.812073",
"id":"9021014017260000",
"idx":"5"
},
Now I want the name from the JSON document depending on what the user inputs.
how do I do this with code?
My code that is wrong is like this :
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JSONReader {
private String jsonData = "";
public String getJsonData(String location){
try {
URL url = new URL("http://api.vasttrafik.se/bin/rest.exe/v1/location.name?authKey=secret&format=json&jsonpCallback=processJSON&input=" + URLEncoder.encode(location, "UTF-8"));
URLConnection connection = url.openConnection();
BufferedReader readJsonFile = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String temp = "";
while((temp = readJsonFile.readLine()) != null){
jsonData += temp;
}
readJsonFile.close();
System.out.println(jsonData);
return jsonData;
}
catch (IOException e) {
}
return null;
}
public void JSONParsing(){
String location = Planner.getPlanner().getStartingLocation();
JSONObject obj =(JSONObject)JSONValue.parse(getJsonData(location));
//Set the text into the JList
if (obj.containsValue(location));
obj.get("name");
}
}
I want get the same name of the location out from the JSON as the user inputs.
How do I do this with code?
I think that you are asking how to parse your JSONObject and get the corresponding values out of it that the user is interested in. Below is an example of how you can pull apart the JSONObject to create a Map whose key is the String id (since the name does not seem to be unique) and whose value is the whole JSONObject. You can use this map to lookup the input from the user and find the appropriate LLA if that's what you are interested in.
public Map<String, JSONObject> createLocationMap(JSONObject jsonObj){
Map<String, JSONObject> nameToLocationMap = new HashMap<String, JSONObject>();
JSONObject locationList = (JSONObject) jsonObj.get("LocationList");
JSONArray array = (JSONArray) locationList.get("StopLocation");
for (int i = 0; i < array.length(); i++) {
String name = (String) ((JSONObject) array.get(i)).get("id");
nameToLocationMap.put(name, ((JSONObject)array.get(i)));
}
return nameToLocationMap;
}
You can tailor this method as you see fit. For example if you are interested in the relationship between the id and the name then you can create a similar method that uses those values instead of id and the entire JSONObject'. I hope that this helps~

Categories