have a structure for a contact book:
Contact { "Name":{ "First name":"Erm","Last Name": "Smith" }, "Number":67485647 }.
I save it as a Json object and than store it in a file with createContact().
public synchronized void createContact (String fname, String lname,String typeof, int number) throws FileNotFoundException
{
JsonObjectBuilder contactBuilder = Json.createObjectBuilder();
JsonObjectBuilder nameBuilder = Json.createObjectBuilder();
JsonArrayBuilder contactArrayBuilder= Json.createArrayBuilder();
nameBuilder.add("First Name",fname);
nameBuilder.add("Last Name",lname);
contactBuilder.add("Name", nameBuilder);
contactBuilder.add("Type", typeof);
contactBuilder.add("number", number);
JsonObject contact = contactBuilder.build();
contactArrayBuilder.add(contact);
JsonArray contactArray=contactArrayBuilder.build();
//write to file
OutputStream os = new FileOutputStream(filename);
JsonWriter fileWriter = Json.createWriter(os);
fileWriter.writeArray(contactArray);
fileWriter.close();
}
I read the file with:
InputStream is = new FileInputStream(filename);
JsonReader fileReader = Json.createReader(is);
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readObject());
JsonArrayBuilder contactArrayBuilder= Json.createArrayBuilder();
This is when I get the error
javax.json.JsonException: Cannot read JSON object, found JSON array
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:105)
I am using javax.json
The problem is that you are storing a JsonArray in that file, and then trying to read that JsonArray as a JsonObject. What you can do to get your code to work is remove these lines:
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readArray());
JsonArrayBuilder contactArrayBuilder= Json.createArrayBuilder();
and replace them with something like this:
JsonArray array = fileReader.readArray();
In the end, reading the file will look like this:
InputStream is = new FileInputStream(filename);
JsonReader fileReader = Json.createReader(is);
JsonArray array = fileReader.readArray();
Change this line
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readObject());
to this
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readArray());
as you are expecting an array but reading the object you are getting this error.
Related
For the below Json payload I'am trying to get the first array element of email_address.
However using the below code I get email address but with the array bracket and quotes like: ["test#test.com"].
I need only the email address text. First element array.
Payload:
{
"valid":{
"email_addresses":[
"testauto#test.com"
]
}
}
Code:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(jsonfilepath));
JSONObject jsonObjects = (JSONObject) parser.parse(jsonObject.get("valid").toString());
String email = jsonObjects.get("email_addresses").toString();
System.out.println("Email address:"+email);
Maybe this unitTest could help you
#Test
public void test() throws JSONException, FileNotFoundException {
JSONObject json = new JSONObject(new JSONTokener(new FileInputStream(new File(jsonfilepath))));
JSONObject valid = (JSONObject) json.get("valid");
Object emailAdresses = valid.get("email_addresses");
if (emailAdresses instanceof JSONArray) {
JSONArray emailAdressArray = (JSONArray) emailAdresses;
Object firstEmailAdress = emailAdressArray.get(0);
System.out.println(firstEmailAdress.toString());
}
}
You could use JSONArray to get the array values:
JSONArray emailAddresses = (JSONArray) jsonObjects.get("email_addresses");
String email = emailAddresses.getJSONObject(0).toString()
System.out.println("Email address: " + email);
Even though I strongly encourage using gson to parse json instead of doing this way, it makes life easier.
Hello i have a json file with data exists like this
[
{
"employee": {
"firstName": "Rudi",
"lastName": "Anton"
}
},
{
"employee": {
"firstName": "Syafira",
"lastName": "Zarakaria"
}
}
]
I want to append json data to this file.
My code now not appending data, re-write file.
Help me
This is my code
JSONObject employeeDetails = new JSONObject();
employeeDetails.put("firstName", "Justin");
employeeDetails.put("lastName", "Saklitinov");
JSONObject employeeObject = new JSONObject();
employeeObject.put("employee", employeeDetails);
JSONObject employeeDetails2 = new JSONObject();
employeeDetails2.put("firstName", "Zara");
employeeDetails2.put("lastName", "Lovez");
JSONObject employeeObject2 = new JSONObject();
employeeObject2.put("employee", employeeDetails2);
//Add employees to list
JSONArray employeeList = new JSONArray();
employeeList.add(employeeObject);
employeeList.add(employeeObject2);
//Write JSON file
try{
String strPath = "employee.json";
File strFile = new File(strPath);
boolean fileCreated = strFile.createNewFile();
//File appending
Writer objWriter = new BufferedWriter(new FileWriter(strFile));
//objWriter.write(employeeList.toJSONString());
objWriter.flush();
objWriter.close();
out.flush();
out.print("OK");
} catch (IOException e) {
e.printStackTrace();
}
You should read the json file into an JSONArray. Add new employee data to this JSONArray and write it to the file. I have modified some of your code.
// Read json file
String jsonFileStr = new String(
Files.readAllBytes(Paths
.get("PATH TO YOUR EMPLOYEE JSON")),
StandardCharsets.UTF_8);
System.out.println(jsonFileStr);
JSONArray jsonArray = (JSONArray) new JSONParser().parse(jsonFileStr);
// Create employee data to be add to json file
JSONObject employeeDetails = new JSONObject();
employeeDetails.put("firstName", "Justin");
employeeDetails.put("lastName", "Saklitinov");
JSONObject employeeObject = new JSONObject();
employeeObject.put("employee", employeeDetails);
JSONObject employeeDetails2 = new JSONObject();
employeeDetails2.put("firstName", "Zara");
employeeDetails2.put("lastName", "Lovez");
JSONObject employeeObject2 = new JSONObject();
employeeObject2.put("employee", employeeDetails2);
// Add data to jsonArray read from json file
jsonArray.put(employeeObject);
jsonArray.put(employeeObject2);
// Writing the jsonArray back to file
String strPath = "PATH TO EMPLOYEE JSON";
File strFile = new File(strPath);
boolean fileCreated = strFile.createNewFile();
Writer objWriter = new BufferedWriter(new FileWriter(strFile));
objWriter.write(jsonArray.toString());
objWriter.flush();
objWriter.close();
Note: You might want to reconsider using the same key 'employee' multiple times in the json.
Try BufferedWriter it open a file in append mode.
BufferedWriter out = new BufferedWriter(
new FileWriter(fileName, true));
out.write(str);
out.close();
yes if you are reading as object and writing as on object. It is a overwrite on the same file.
I want to use json encoded array which i am return from this link :
http://sids.roundone.asia/suggest.json?data=soft
as suggestions in android application.
(I have used json_encode($arr) function in php file and i am returning that as response for above link)
I have a problem in reading this response in java and storing it in an ArrayList.
My code is :
try {
String temp=sName.replace(" ", "%20");
URL js = new URL("https://sids.roundone.asia/suggest.json?data="+temp);
URLConnection jc = js.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
JSONArray jsonArray = jsonResponse.getJSONArray("results");
for(int i = 0; i < jsonResponse.length(); i++){
JSONObject r = jsonArray.getJSONObject(i);
ListData.add(new SuggestGetSet(jsonResponse.get(String.vlaueOf(iss)));
}
}
As I could see on your link, you're returning a JSON Array, instead of a JSON Object, ( "[ ]" instead of "{ }") and then in your java code you're trying to create a JSONObject here:
JSONObject jsonResponse = new JSONObject(line);
Try changing that to:
JSONArray jsonResponse = new JSONArray(line);
You return JSON array directly not a JSON Object have inner array so cast your incoming response to JSONArray directly.
JSONArray jsonResponse = new JSONArray(line);
I'm new in java and i have this maybe simple faculty project. I must to parse json with eclipse, so i started but without any success. I don't know how to start when i have a multiple object in json.
I started like this:
public static void main(String[] args) {
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray objectArray = jsonObject.getJSONArray("product");
//JSONObject site= jsonSites.getJSONObject(1);
long elementaryProductId = (long) jsonObject[0].get("elementaryProductId");
System.out.println("The id is: " + elementaryProductId);'
And thi is my json file:
[{
"elementaryProductId":1,
"bonusMalus":30,
"deductible":500,
"comprehensive":1,
"partial":0,
"legacyPremium":130,
"product":{
"productId":2,
"garage":"true",
"constructionYear":1990,
"region":"East",
"dateOfBirthYoungest":"1983-06-22",
"objectValue":25000,
"type":"Car",
"insuredObject":{
"name":"Car",
"ownersName":"Jovana",
"mileage":300000,
"engineCapacity":120
},
"salesProduct":{
"salesProductId":3,
"currency":"EUR",
"contractStart":"2011-01-01",
"contractEnd":"2012-01-01"
},
"productType":"Car"
}
},
{
"elementaryProductId":1,
"bonusMalus":5,
"deductible":100,
"comprehensive":1,
"partial":0,
"legacyPremium":75.38,
"product":{
"productId":2,
"garage":"true",
"constructionYear":2005,
"region":"East",
"dateOfBirthYoungest":"1999-06-22",
"objectValue":30000,
"type":"Car",
"insuredObject":{
"name":"Car",
"ownersName":"Jelena",
"mileage":300000,
"engineCapacity":210
},
"salesProduct":{
"salesProductId":3,
"currency":"EUR",
"contractStart":"2013-01-01",
"contractEnd":"2014-01-01"
},
"productType":"Car"
}
}]
I got it to work with the following:
public static void main(String[] args) throws IOException, ParseException{
FileReader reader = new FileReader(new File("filename.json"));
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
JSONObject object = (JSONObject) jsonArray.get(0);
long elementaryProductId = (Long) object.get("elementaryProductId");
System.out.println("The id is: " + elementaryProductId);
}
Explanation of the above:
You know the outermost element is an array so parse straight into a JSONArray. Next you want to pull out the first element of that array which is a JSONObject (its in braces). After that the code should be fairly self explanatory :)
My String array has the following output each time it iterates through the loop
apple
orange
I want to convert my string array output to json format/jsonarray. I tried but it gives output as
{"fruits",apple}
{"fruits",orange}
I want my output as
{"fruits": [
{
"1": "apple"
}
{
"2": "orange"
}
I tried the below code
String[] strArray = new String[] {newString};
JSONObject json=new JSONObject();
//json.put("fruits", newString);
//System.out.println(json);
for(int i=0;i<strArray.length;i++)
{
System.out.print(strArray[i]+"\t");
json.put("",strArray[i]);
}
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
for(int i=0;i<strArray.length;i++)
{
JSONObject fruit = new JSONObject();
fruit.put(""+i,strArray[i]);
array.put(fruit);
}
obj.put("Fruits",array);
System.Out.Println(obj.toString(2));
Try below code :-
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("key", "value");
String jsonString = jsonObject.toString();
I hope this will work for you.