Reading Multiple JSONObjects from a file - java

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"
}]

Related

How to modularize the code for JsonObject and JsonArray to read Json files at class level. Which I am using later to write Testcases

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

Getting value from an array in a JSON Object in Java?

I'm fairly new to REST API calls in Java and I'm currently encountering problems with trying to get the "item" section from the JSON object (below). I guess it also confuses me that "response" is an object in an array too?/
The JSON file is below:
{
"version": "1.0",
"code": 200,
"request":{"text":["seafood" ], "lang": "en", "type": "stimulus"},
"response":[{
"text": "seafood",
"items":[
{"item": "Shrimp", "weight": 100, "pos": "noun" },
{"item": "Lobster",…
]
}]
}
I have currently managed to get the "response" part of the object using:
BufferedReader in = new BufferedReader(
new InputStreamReader(conection.getInputStream()));
StringBuffer json = new StringBuffer();
while ((readLine = in.readLine()) != null) {
json.append(readLine);
}
in.close();
JSONParser parser = new JSONParser();
try{
JSONObject object= (JSONObject) parser.parse(json.toString());
Object response = json.get("response");
...
Up to this point, I get stuck. I don't know what to do to 'response' to get to "items", and if I try to cast 'response' as a JSONObject, it will return as null?
What I want to try and do is to get each "item" in the "items" part and put it in a list.
Help would be very much appreciated!
I think it should works:
JSONParser parser = new JSONParser();
try{
JSONObject object= (JSONObject) parser.parse(json.toString());
JSONArray response = object.getJSONArray("response");
JSONObject responseObject = response.getJSONObject(0);
JSONArray expectedArray = responseObject.getJSONArray("items");
for (int i = 0; i < expectedArray.length(); i++) {
String item = expectedArray.getJSONObject(i).getString("item");
String weight = expectedArray.getJSONObject(i).getInt("weight");
......
//Here you can create your custom object and add to your array. For example
list.add(new MyOwnObject(item, weight));
}
....
Because response is array, not object
You should check the documentation for JSONObject. It describes all of the methods which are available. Note that there is no method named get(). Instead, you probably want to use getJSONArray()

Java Array response instead of brackets

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

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
}

Writing to a json file is not in correct format

I am creating a java project which writes data to an already existing json file.I am using gson libraries to write.The problem is when i write the json it written at the end of the file not inside.Here is my json before i run the program
{
"trips":[
{
"tripname":"Goa",
"members":"john"}
]
}
here is my java code
FileOutputStream os=new FileOutputStream(file,true);
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
Gson gson=new GsonBuilder().setPrettyPrinting().create();
String temp=gson.toJson(trips);
bw.append(temp);
bw.close();
and here is my output json
{
"trips":[
{
"tripname":"Goa",
"members":"john"}
]
}{
"tripname": "trip1",
"members": "xyzxyz"
}
the newly added must be inside the trips array how can i achieve it.
The problem is that you are not using Gson. You need to have Java Bean with proper Gson annotaions and with this use Gson to serialize.
Look at this example: https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples
Edit
More or less it would look like this:
public class Trip implements Serializable {
private String tripName;
private String members;
// getters setters
}
Using Gson:
List<Trip> trips = new ArrayList<>();
// add to list
Gson gson = new Gson();
// to json
String json = gson.toJson(trips)
// from json
Type collectionType = new TypeToken<Collection<Trip>>(){}.getType();
List<Trip> trips2 = gson.fromJson(json, collectionType);

Categories

Resources