Java Array response instead of brackets - java

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);
}
}
}

Related

Using vararg to get data from nested JSON Object returns null

I am trying to return data from a nested JSON Object in a seperate JSON file. For example, my JSON file might look like this
{
"user1": {
"name": "John",
"age": 25,
"job": "developer"
},
"day": "May 2nd 2022"
}
And here is the method that I am using to pull the nested Object
public static Object get(String key, String... objKey) throws Exception {
//create new JSON parser and FileReader
JSONParser parser = new JSONParser();
FileReader jsonFile = new FileReader(path);
//Reads the data in JSON file and assigns to Object jsonData
Object jsonData = parser.parse(jsonFile);
//assigns data to a JSONObject object
JSONObject jsonDataObj = (JSONObject) jsonData;
//checks to see if data is an array
if(jsonDataObj.get(key).getClass().isArray()){
throw new Error("Data is an array and not returnable");
}
if(jsonDataObj.get(key) instanceof JSONArray){
//get JSON Object into JSONObject variable to read from
JSONObject jsonObj = (JSONObject) jsonDataObj.get(key);
//get wanted data from nested JSON Object
Object wantedData = jsonObj.get(objKey);
return wantedData;
} else {
//get data associated with 'key' value in JSON Object
Object wantedData = jsonDataObj.get(key);
return wantedData;
}
} //end get()
When I call the method get() with only one param like get("day") it returns the data in day perfectly fine and nothing goes wrong. The problem is when I call the method and introduce a second argument it returns null.
For example, if I call get("user1", "age") instead of returning 25 is return null. I figured out that it is the vararg parameter that is messing it up since when I change the method parameters to String key, String objKey it works fine. Another thing that i've noticed while debuging is that if I print the vararg it prints a memory address instead of the String passed to the parameter.
If it is of any help; I am using the json-simple library on Maven 1.4

how to get custom data from API in Java

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.

Find JSON object in JSON array

I have a goal to verify that certain JSON that I've got from RabbitMQ corresponds to one of expected JSONs in an array in a single file.
In other words, I need to verify that this JSON:
{
"networkCode":"network",
"programId":"92000"
}
is present in this JSON array:
[
{
"networkCode":"network",
"programId":"92000"
},
{
"networkCode":"network",
"programId":"92666"
}
]
Thank you very much for help!
Some part of my code
//GET DESIRABLE JSON
String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
JSONObject myJSON= new JSONObject(message);
//GET THE JSON ARRAYS FROM FILE
JSONParser parser = new JSONParser();
Object expectedJSONs= parser.parse(new FileReader("C:\\amqpclient\\src\\test\\java\\tradeDoubler\\ExpectedDTO.json"));
JSONArray expectedArray = (JSONArray) expectedJSONs;
JSONAssert.assertEquals(
myJSON, expectedArray , JSONCompareMode.LENIENT);
Compilation says that cannot resolve this
Exception in thread "main" java.lang.AssertionError: Expecting a JSON array, but passing in a JSON object
Org.json library is quite easy to use.
Example code below:
import org.json.*;
JSONObject obj = new JSONObject(" yourJSONObjectHere ");
JSONArray arr = obj.getJSONArray("networkArray");
for (int i = 0; i < arr.length(); i++)
{
String networkCode = arr.getJSONObject(i).getString("networkCode");
......
}
By iterating on your JSONArray, you can check if each object is equal to your search.
You may find more examples from: Parse JSON in Java
May I suggest you to use the Gson Library?
You can use something like this. But It will throw an exception if the json doesn't match/contains the fields.
Type listType = new TypeToken<ArrayList<YourJavaClassJsonModel>>() {
}.getType();
List<YourJavaClassJsonModel> resultList = gson.fromJson(JsonString, listType);
Hope it may help
You could use a JSON parser to convert the JSON to a Java object (Jackson and GSON are good options), and then check that object.

Converting a string in JSON object and validating

I am trying to validate this string below. Actually I am receiving this string in my servlet, now I need to validate these values at backend. What is the right way to do so. Shall I first convert it to JSON Object then to HashMap? Please suggest the correct/appropriate approach to be used here. I am quite new to Java and JSON.
String is
"{"if_ack":4},{"if_cmd":1,"if_state":1},{"if_cmd":1,"if_state":5}"
I am using GSON for processing JSON at server. For example:
InputStream is (send by client, JSON format)
Reader reader = new InputStreamReader(is);
Gson gson = new Gson();
List<YourClass> items = gson.fromJson(reader, new TypeToken<List<YourClass>>()
YourClass should have attributes like if_ack, if_state, if_cmd,...
Then you use as simple as this:
for (YourClass item : items) {
//do whatever you want
}
EDIT: your string should be in correct JSON format like this (JSON array): [{"if_ack":4}, {"if_cmd":1,"if_state":1}, {"if_cmd":1,"if_state":5}]
EXAMPLE:
You have JSON like this : [{"id": "1", "image": "test1"}, {"id": "2", "image": "test2"}]
YourClass.java should be:
public class YourClass{
private int id;
private String image;
//+ constructor, getters, setters,...
}
On server you can receive JSON from client side by InputStream is:
Reader reader = new InputStreamReader(is, "UTF-8");
Gson gson = new Gson();
List<YourClass> items = gson.fromJson(reader, new TypeToken<List<YourClass>>();
and then:
for (YourClass item: items){
//acces to item properties like item.id, item.image
}

Reading Multiple JSONObjects from a file

I am storing an arraylist of Objects in JSON format in a file. As soon as new arraylist appears it converts the object in JSON format and append it in the file.The encoding works fine. But while decoding it throws exception. I am quite new in this field and learning.Any help is welcome.
Encoding Code
public static void jsondumpfile(ArrayList<HtmlElementObject> sanitizelog)
{
try {
File file = new File("c:\\temp\\auditinfojson.json");
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fileWriter);
Gson gson=new Gson();
//bw.append("---------------");
//bw.append(gson.toJson(sanitizelog));
//fw.append(gson.toJson(sanitizelog));
for(HtmlElementObject eachobj : sanitizelog)
{
bw.write(gson.toJson(eachobj));
}
//bw.flush();
bw.close();
logElementData.clear();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
RESULTANT FILE AFTER ENCODING
{"appLoginId":1058,"tabId":"1","elementType":"Image","label":"No Image Name","value":"https://admin.xyz.com","seqTrail":"No possible trail sequence","timeStamp":"2014-01-31 13:02:42.618"}
{"appLoginId":1058,"tabId":"1","elementType":"Image","label":"No Image Name","value":"https://admin.xyz.com/xyz/images/btn-cancel.gif","seqTrail":"No possible trail sequence","timeStamp":"2014-01-31 13:02:42.625"}
Like this multiple objects are stored.
DECODING/PARSING BACk CODE
public static void extractfromjson() throws IOException
{
ArrayList<HtmlElementObject> tCollection = new ArrayList<HtmlElementObject>();
Gson gson = new Gson();
BufferedReader bufferedReader = new BufferedReader(new FileReader(
"c:\\temp\\auditinfojson.json"));
Type type = new TypeToken<ArrayList<HtmlElementObject>>(){}.getType();
ArrayList<HtmlElementObject> J_tweet = (ArrayList<HtmlElementObject>)gson.fromJson(bufferedReader, type);
System.out.println(J_tweet);
}
EXCEPTION THROWN
**com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2**
This comes when i want to retrieve the data.
When we have a JSON, the GSON fails to parse this in to Java class which has field of type List class, When JSON data comes with matches as “Object” format, it throws exception “Expected BEGIN_ARRAY but was BEGIN_OBJECT”.
This guy, https://github.com/sacdroid did a Java adapter to Fix it problem.
You can use these classes bellow, then while constructing GSON instance, you have to assign TypeAdapterFactory with ArrayAdapterFactory to GsonBuilder.
Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create();
ArrayAdapter.java
http://sachinpatil.com/downloads/code/ArrayAdapter.java
ArrayAdapterFactory.java
http://sachinpatil.com/downloads/code/ArrayAdapterFactory.java
PS: In this case, you had problem with you JSON, your JSON content wasn't a Valid, I fix it putting [ ] (brackets) between the { }'s and ,(comma) to separate :
[{
"appLoginId": 1058,
"tabId": "1",
"elementType": "Image",
"label": "No Image Name",
"value": "https://admin.xyz.com",
"seqTrail": "No possible trail sequence",
"timeStamp": "2014-01-31 13:02:42.618"
}, {
"appLoginId": 1058,
"tabId": "1",
"elementType": "Image",
"label": "No Image Name",
"value": "https://admin.xyz.com/xyz/images/btn-cancel.gif",
"seqTrail": "No possible trail sequence",
"timeStamp": "2014-01-31 13:02:42.625"
}]

Categories

Resources