I thanks for taking a look.
I'm working on a problem where I need to be able to get a Json into memory and be able to "navigate" around the keys.
I am able to use the Json.createParser() method and use the FileReader in the args to get the file in my system. My problem is that from there I don't yet have a way to take the JsonParser object to JsonObject to read values from.
I am using the package javax.json.
I want to be able to navigate around the Json data I have easily with JsonObject and JsonArray but using the JsonParser object.
Thanks for your time.
Okay I figured it out.
Here is what the json looks like:
{
"name": "Changed name",
"Items":
[
{"item1": "the_fist_item"},
{"item2": "the_second_item"},
{"item3": "the_second_item"}
]
}
then inside the java...
import java.io.FileReader;
import javax.json.*;
public class JsonTester
{
public static void main(String[] args)
{
try
{
JsonReader json_file = Json.createReader(new FileReader("***the directory to the json file***"));
JsonObject json_object = json_file.readObject();
String the_second_item = json_object.getJsonArray("Items").getJsonObject(1).get("item2").toString();
System.out.println(the_second_item);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
The navigating part I was trying to accomplish is on the_second_item. Which is all the get() methods to go deeper into the Json file to get the specific value I wanted.
Thanks to David Ehrmann for his help.
Related
Iam using this API -> https://www.boredapi.com/api/activity
So Iam creating a program in Java but when i retrieve data from this above API
like this ->
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class apiTest {
public static void main(String[] args) {
String ApiFRomData;
try {
URL url_name = new URL("https://www.boredapi.com/api/activity");
BufferedReader sc = new BufferedReader(new InputStreamReader(url_name.openStream()));
// reads public IPAddress
ApiFRomData = sc.readLine().trim();
} catch (Exception e) {
ApiFRomData = "Cannot Execute Properly";
// return "connection_issue";
}
// return "nothinng";
System.out.println(ApiFRomData);
}
}
I get this output in console ->
{
"activity": "Learn Express.js",
"accessibility": 0.25,
"type": "education",
"participants": 1,
"price": 0.1,
"link": "https://expressjs.com/",
"key": "3943506"
}
but i want a custom output for example...I only want the activity not that {}bracket or that other stuff price, type etc.
I only want the particular custom output
In short how can I get only activity line in output.
please help me :)
What you see is JSON. That is a format very widely used to transfer data around.
What you need is a JSON Java Library. It can be used to access fields of JSON objects and even turn them into Java Objects.
Here is a small example with the library I referenced above:
JSONObject jsonObject = new JSONObject(jsonString); // jsonString is what you recieve from your call to the API
// It will be the same as accessing a HashMap [key1 -> value1, key2 -> value2...]
// Now you can access whatever you need from this jsonObject like this:
System.out.println(jsonObject.getString("activity"));
Of course you could use your code to do this, but why reinvent the wheel?
Just import this library and you're good to go.
I am using GSON library to read JSON file for my automation. For which I need to read file and then create a object of json while traversing the JSON.
Later I am using these objects to to modify the JSON..
I want to reduce the code for traversing down the json as many objects are getting created.
Though this works perfectly fine. Just I need to modularize the code.
Adding the code with the URL , Response and User JSON
Url.json
{"emplyee":
{"addemplyee": "<URL>/emplyee","addemplyee": "<URL>/editemplyee"}
}
Response .json
[
{"success":true},
{"success":false}
]
emplyee.json
{
"addemplyee":
{"details":{
"lst":"lastname",
"id":"username",
"Password":"password"
}
},
"editemplyee":
{ "details":{
"Password":"password"
}}}
Actual
Currently I am creating multiple objects to read ths jOSN file and later with the use of same I am updating my JSON.
Expected
Can I modularize this approach of code.
Yes you can:
public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); //you can reuse gson as often as you like
public <T> static T readJson(String file){
try{
FileReader fr = new FileReader(new File(file)); //gson takes a filereader no need to load the string to ram
T t = GSON.fromJson(fr, T.getClass());
fr.close(); //close the reader
return t;
}catch(Error e){
//ignore or print, if you need
}
}
I am trying to parse a JSON response in Java but am facing difficulty due to the response being array format, not object. I, first, referenced the this link but couldn't find a solution for parsing the JSON properly. Instead, I am receiving this error when trying to display the parsed data...
Exception in thread "main" org.json.JSONException: JSONObject["cardBackId"] not found.
Snippet for displaying data:
JSONObject obj = new JSONObject(response);
JSONArray cardBackId = (JSONArray) obj.get("cardBackId");
System.out.println(cardBackId);
Data response via Postman:
[
{
"cardBackId": "0",
"name": "Classic",
"description": "The only card back you'll ever need.",
"source": "startup",
"sourceDescription": "Default",
"enabled": true,
"img": "http://wow.zamimg.com/images/hearthstone/backs/original/Card_Back_Default.png",
"imgAnimated": "http://wow.zamimg.com/images/hearthstone/backs/animated/Card_Back_Default.gif",
"sortCategory": "1",
"sortOrder": "1",
"locale": "enUS"
},
While without JSONObject I am pulling the data fine in Java and verified by using response.toString in STDOUT, this is my first time using json library in Java and it is important I parse this data as json. Any advice with this is helpful.
The response is an array and not object itself, try this:
JSONObject obj = new JSONArray(response).getJSONObject(0);
String cardBackId = obj.getString("cardBackId");
Here is the output, along with relevant files used:
First parse the response as JsonArray, instead of JsonObject.
Get JsonObject by iterating through the array.
Now get the value using the key.
Look at this example using Gson library, where you need to define the Datatype to define how to parse the JSON.
The key part of the example is: Data[] data = gson.fromJson(json, Data[].class);
package foo.bar;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Main {
private class Data {
long cardBackId;
String name;
}
public static void main(String[] args) throws FileNotFoundException {
// reading the data from a file
BufferedReader reader = new BufferedReader(new FileReader("data.json"));
StringBuffer buffer = new StringBuffer();
reader.lines().forEach(line -> buffer.append(line));
String json = buffer.toString();
// parse the json array
Gson gson = new Gson();
Data[] data = gson.fromJson(json, Data[].class);
for (Data item : data) {
System.out.println("data=" + item.name);
}
}
}
I am using a httprequest to get Json from a web into a string.
It is probably quite simple, but I cannot seem to convert this string to a javax.json.JsonObject.
How can I do this?
JsonReader jsonReader = Json.createReader(new StringReader("{}"));
JsonObject object = jsonReader.readObject();
jsonReader.close();
See docs and examples.
Since the above reviewer didn't like my edits, here is something you can copy and paste into your own code:
private static JsonObject jsonFromString(String jsonObjectStr) {
JsonReader jsonReader = Json.createReader(new StringReader(jsonObjectStr));
JsonObject object = jsonReader.readObject();
jsonReader.close();
return object;
}
I know this is an outdated question and that this answer would not be relevant years back, but still.
Using Jackson Library is the easiest technique to solve this problem.
Jackson library is an efficient and widely used Java library to map Java objects to JSON and vice-versa. The following statement converts JSON String representing a student into a Java class representing the student.
Student student = new ObjectMapper().readValue(jsonString, Student.class);
Using Jackson to parse a string representation of a json object into a JsonNode object.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class J {
public static void main(String[] args) throws JsonProcessingException {
var json =
"""
{
"candle": {
"heat": 10,
"color": "orange"
},
"water": {
"heat": 1,
"color": null
}
}
""";
ObjectMapper mapper = new ObjectMapper();
var node = mapper.readTree(json);
System.out.println(node.toPrettyString());
}
}
I am trying below code....
public String listToJsonString(String keyName, List<StyleAttribute> attrs) {
JSONObject json = new JSONObject();
json.accumulate(keyName, attrs);
return json.toString();
}
But when i am checking json variable it contains empty values something like below
{"myKey":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]}
And when i am checking attrs variables it contains 22 element Data.What i am doing Wrong here? I am just converting my List to Json Object and save to Database.
I am using
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
You can use below code
public String listToJsonString(List<StyleAttribute> attrs) {
JSONObject jObject = new JSONObject();
try {
JSONArray jArray = new JSONArray();
for (MyClass myObject: attrs) {
JSONObject styleJSON = new JSONObject();
styleJSON.put("name",myObject.getName());
styleJSON.put("rollNumber", myObject.getRollNumber());
jArray.add(styleJSON);
}
jObject.put("keyName", jArray);
} catch (Exception jse) {
}
return jObject.toString();
}
It will resolve your issue.
Not sure on this one but maybe the objects in your List are serializable.
Also, what library do you use to manage JSON?
EDIT :
So json-lib it is!
I found this in the json-lib FAQ :
Json-lib creates empty JSONObjects from my bean class, help me!
Json-lib uses the JavaBeans convention to inspect your beans and create
JSONObjects. If the properties of your beans do not adhere to
the convention, the resulting JSONObject will be empty or half empty.
You must provide a read/write method pair for each property.
Here's the wikipedia page talking about the JavaBeans conventions:
http://en.wikipedia.org/wiki/JavaBeans#JavaBean_conventions
Hope this will help you!