JSONParser: Unexpected token COLON(:) - java

I am trying to parse a json file with JSONParse and am getting this error, with the error occurring in beginning of the following json:
Unexpected token COLON(:) at position 11.
{"276716878": {
"followers": [
2435018580,
1664252310,
372262434
],
"following": [
16211434,
945440959,
130682467,
264257750,
900526363,
318231688,
40335029,
64044676
]
}}
I also wrote the json file with the following:
FileWriter out = new FileWriter(JSON_FILE);
out.write(json.toString(1));
out.flush();
out.close();

There could be some format error in the json string you passed. Validate your json string. The below sample code works fine.
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
private static final Logger logger = Logger.getLogger(Test.class.getName());
private static final String JSON_FILE = "/home/visruth/Desktop/Visruth.txt";
public static void main(String[] args) {
String jsonText = "{\"215876567\": { \"followers\": [ 2464054938, 772677937]}}";
try (
FileWriter out = new FileWriter(JSON_FILE);
) {
JSONObject json = new JSONObject(jsonText);
int indentFactor = 1;
String prettyprintedJSON = json.toString(indentFactor);
System.out.println(prettyprintedJSON);
out.write(prettyprintedJSON);
} catch (JSONException e) {
logger.log(Level.SEVERE, e.getMessage());
} catch (IOException e) {
logger.severe(e.getMessage());
}
}
}
Assign your json text in jsonText variable and try.

I think you are referring classes from different apis for this purpose. Just use only one api.
Here is a demo code which works fine with the given json string in the question.
import java.io.FileWriter;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.junit.Assert;
import org.junit.Test;
public class TestCase {
private static final String JSON_FILE = "/home/visruth/Desktop/Visruth.txt";
#Test
public void testJSONParser() throws Exception {
JSONParser parser = new JSONParser();
try (
FileWriter out = new FileWriter(JSON_FILE);
) {
String jsonText = "{\"276716878\": { \"followers\": [ 2435018580, 1664252310, 372262434 ], \"following\": [ 16211434, 945440959, 130682467, 264257750, 900526363, 318231688, 40335029, 64044676 ] }}";
Object obj = parser.parse(jsonText);
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonObject215876567 = (JSONObject)jsonObject.get("276716878");
JSONArray followers = (JSONArray)(jsonObject215876567.get("followers"));
Assert.assertEquals("[2435018580,1664252310,372262434]", followers.toString());
String jsonStringFromJsonObject = jsonObject.toString();// There is no argument as an int
out.write(jsonStringFromJsonObject);
} catch (ParseException e) {
Assert.fail(e.getMessage());
}
}
}

Related

Getting error while trying to read a file content from a json file

Ask: I am trying to capture the values captured inside key "value" and display it on console. However when executed getting error as"org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject"
Code Written:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class FileExtractJSON
{
public static void main(String[] args) throws Exception
{
JSONParser parser = new JSONParser();
try
{
System.out.println("Reading JSON file from Java program");
FileReader fileReader = new FileReader("C:\\Users\\shisyadav\\Desktop\\HP Remainco\\JSON Objects\\directkafkaconsumer_actual.json");
JSONObject value_expected = (JSONObject) parser.parse(fileReader);
JSONArray jsonObject = (JSONArray) value_expected.get("value");
Iterator i = jsonObject.iterator();
System.out.println("Values:");
while (i.hasNext())
{
System.out.println(""+i.next());
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
Sample file from which we are trying to capture value against key "value"
Your file has JSONArray, not JSONObject. Check your Json has [] at the begining.
JSONObject value_expected = (JSONObject) parser.parse(fileReader);
So this line(top) should be this (below)
JSONArray value_expected = (JSONArray) parser.parse(fileReader);

Unable to parse the key and value of nested json file using java

Below is the json file i am trying to parse.I want to print all key and corresponding values.
{
"A":{
"name":"Ram",
"gender":"male",
"designation":"engineer"
},
"B":{
"name":"Shyam",
"gender":"male",
"designation":"student"
},
"C":{
"name":"Mohan",
"gender":"male",
"designation":"manager"
}
}
I have tried the following code:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
public class FetchJsonNested {
public static void main(String args[]) throws FileNotFoundException {
try {
JSONParser jp=new JSONParser();
Object obj=jp.parse(new FileReader("C:\\Users\\DELL\\Documents\\NetBeansProjects\\WaterNetwork\\web\\kusharray.json"));
JSONObject job=(JSONObject)obj;
Iterator < ? > keys = job.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
System.out.println(key);
if (job.get(key) instanceof JSONObject) {
System.out.println(job.get(key));
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
I have read stuffs from many site but no one is working like the way i want.I want to print all keys and corresponding values.
Using org.json as you did in your example :
String jsonStr = "{\"A\":{\"name\":\"Ram\",\"gender\":\"male\",\"designation\":\"engineer\"},\"B\":{\"name\":\"Shyam\",\"gender\":\"male\",\"designation\":\"student\"},\"C\":{\"name\":\"Mohan\",\"gender\":\"male\",\"designation\":\"manager\"}}";
JSONObject json = new JSONObject(jsonStr);
for (Object key : json.keySet().toArray()){
JSONObject data = json.getJSONObject(key.toString());
System.out.println("json :" + data.toString());
System.out.println("name :" +data.getString("name"));
System.out.println("gender :" +data.getString("gender"));
System.out.println("designation :" +data.getString("designation"));
}
Now you can replace my first line "String jsonStr = ..." with your file reader.
below follow not the awesome and most elegant solution but this can lead you to what you need.
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) throws Exception {
String jsonString = loadJSONFile();
JsonElement jsonElement = new JsonParser().parse(jsonString);
JsonObject jsonObject = jsonElement.getAsJsonObject();
print(jsonObject);
}
private static String loadJSONFile() throws FileNotFoundException {
Scanner scanner = new Scanner(new FileReader("path/to/the/json/file.ext"));
StringBuilder stringBuilder = new StringBuilder();
while (scanner.hasNext()) {
stringBuilder.append(scanner.next());
}
scanner.close();
return stringBuilder.toString();
}
private static void print(JsonObject jsonObject) {
Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();
for (Map.Entry<String, JsonElement> entry : entries) {
System.out.println(entry.getKey() + ": " + entry.getValue());
try {
JsonElement jsonElement = new JsonParser().parse(String.valueOf(entry.getValue()));
JsonObject innerJsonObject = jsonElement.getAsJsonObject();
print(innerJsonObject);
} catch (Exception e) {
// is not a JSON
}
}
}
}
Output example:
A: {"name":"Ram","gender":"male","designation":"engineer"}
name: "Ram"
gender: "male"
designation: "engineer"
B: {"name":"Shyam","gender":"male","designation":"student"}
name: "Shyam"
gender: "male"
designation: "student"
C: {"name":"Mohan","gender":"male","designation":"manager"}
name: "Mohan"
gender: "male"
designation: "manager"

Write a json file in java

I want to write a json file in java, but it doesn't work, I get this warning:
I want to know how to do this, because I am going to convert a cfg file that is tabbed to json.
Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList<E> should be parameterized
and I have this code:
package json;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonWriter {
public static void main(String[] args) {
JSONObject countryObj = new JSONObject();
countryObj.put("Name", "India");
countryObj.put("Population", new Integer(1000000));
JSONArray listOfStates = new JSONArray();
listOfStates.add("Madhya Pradesh");
listOfStates.add("Maharastra");
listOfStates.add("Rajasthan");
countryObj.put("States", listOfStates);
try {
// Writing to a file
File file=new File("JsonFile.json");
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
System.out.println("Writing JSON object to file");
System.out.println("-----------------------");
System.out.print(countryObj);
fileWriter.write(countryObj.toJSONString());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I would suggest that you just make a simple ArrayList with your objects, and then serialize them into JSON with a serializer (Using the Jacksoin library in the example below). It would look something like this:
First, define your model in a class (Made without incapsulations for readability):
public class Country{
public String name;
public Integer population;
public List<String> states;
}
Then you can go ahead and create it, and populate the list:
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JsonWriter {
public static void main(String[] args) {
Country countryObj = new Country();
countryObj.name = "India";
countryObj.population = 1000000;
List<String> listOfStates = new ArrayList<String>();
listOfStates.add("Madhya Pradesh");
listOfStates.add("Maharastra");
listOfStates.add("Rajasthan");
countryObj.states = listOfStates ;
ObjectMapper mapper = new ObjectMapper();
try {
// Writing to a file
mapper.writeValue(new File("c:\\country.json"), countryObj );
} catch (IOException e) {
e.printStackTrace();
}
}
}

JSON file with a lot of elements, how to read and print using java?

I am very new to JSON. I managed to print out 1 element in the JSON file using Java. However if the file consists of more than 1 element, I do not know how to go about retrieving it. Should I use JSONArray? I tried to search and apply JSONArray, but i got no idea how to. Or does it has something to do with Gson, Jackson thingy? I got no idea what are they..
This is my example.json file:
{"rel": "/r/AtLocation", "weight": 0.5, "dataset": "/d/dbpedia/en", "sources": ["/s/dbpedia/3.7"], "id": "/e/ec1914bfb0606c36376fbbcd316e5666022e2469", "features": ["/c/en/apple_inc /r/AtLocation -", "/c/en/apple_inc - /c/en/unite_state", "- /r/AtLocation /c/en/unite_state"], "end": "/c/en/unite_state", "license": "/l/CC/By-SA", "uri": "/a/[/r/AtLocation/,/c/en/apple_inc/,/c/en/unite_state/]", "start": "/c/en/apple_inc", "context": "/ctx/all", "surfaceText": null}
{"rel": "/r/IsA", "weight": 0.5, "dataset": "/d/dbpedia/en", "sources": ["/s/dbpedia/3.7"], "id": "/e/914e6775fd79d660bacf22ec699568e6694da3e8", "features": ["/c/en/america_beautiful /r/IsA -", "/c/en/america_beautiful - /c/en/national_anthem", "- /r/IsA /c/en/national_anthem"], "end": "/c/en/national_anthem", "license": "/l/CC/By-SA", "uri": "/a/[/r/IsA/,/c/en/america_beautiful/,/c/en/national_anthem/]", "start": "/c/en/america_beautiful", "context": "/ctx/all", "surfaceText": null}
This is my java file:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class test
{
public static void main(String[] args)
{
JSONParser parser = new JSONParser();
try
{
Object obj = parser.parse(
new FileReader("C:/Users/LijingYeo/Desktop/example.json"));
JSONObject jsonObject = (JSONObject) obj;
String rel = (String) jsonObject.get("rel");
System.out.println(rel);
String start = (String) jsonObject.get("start");
System.out.println(start);
String end = (String) jsonObject.get("end");
System.out.println(end);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ParseException e)
{
e.printStackTrace();
}
}
}
All suggestions and helps rendered are sincerely appreciated by me, thank you for your time and effort!
I think you should read your json file line by line and then parse to json object.
This sample code works for your json file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadJsonFile
{
public static void main(String[] args)
{
readJsonFile();
}
public static void readJsonFile() {
BufferedReader br = null;
JSONParser parser = new JSONParser();
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("D:\\example.json"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println("Record:\t" + sCurrentLine);
Object obj;
try {
obj = parser.parse(sCurrentLine);
JSONObject jsonObject = (JSONObject) obj;
String rel = (String) jsonObject.get("rel");
System.out.println(rel);
String start = (String) jsonObject.get("start");
System.out.println(start);
String end = (String) jsonObject.get("end");
System.out.println(end);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Json file is yours as below. I hope this may help.
Whatever you are doing is right.
Your JSON structure is of type JSONObject, i.e (Key, Value) pairs. Of those elements, features element's value is of type JSONArray. So while browsing through the elements, you should cast the value of features element to JSONArray and then iterate through the list of elements in that array.
JSONArray features = (JSONArray) jsonObject.get("features");
int size = features.size();
for (int i = 0; i < size; i++)
{
System.out.println(features.get(i));
}
HTH.
You can use ObjectMapper.
String jsonString = null;
if (prettyPrint == true) {
// this is time consuming
jsonString = myObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(myObject);
} else {
// faster option
jsonString = myObjectMapper.writeValueAsString(myObject);
}

What’s the best way to load a JSONObject from a json text file?

What would be the easiest way to load a file containing JSON into a JSONObject.
At the moment I am using json-lib.
This is what I have, but it throws an exception:
XMLSerializer xml = new XMLSerializer();
JSON json = xml.readFromFile("samples/sample7.json”); //line 507
System.out.println(json.toString(2));
The output is:
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:61)
at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
at net.sf.json.xml.XMLSerializer.readFromStream(XMLSerializer.java:386)
at net.sf.json.xml.XMLSerializer.readFromFile(XMLSerializer.java:370)
at corebus.test.deprecated.TestMain.main(TestMain.java:507)
Thanks #Kit Ho for your answer. I used your code and found that I kept running into errors where my InputStream was always null and ClassNotFound exceptions when the JSONObject was being created. Here's my version of your code which does the trick for me:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
public class JSONParsing {
public static void main(String[] args) throws Exception {
File f = new File("file.json");
if (f.exists()){
InputStream is = new FileInputStream("file.json");
String jsonTxt = IOUtils.toString(is, "UTF-8");
System.out.println(jsonTxt);
JSONObject json = new JSONObject(jsonTxt);
String a = json.getString("1000");
System.out.println(a);
}
}
}
I found this answer to be enlightening about the difference between FileInputStream and getResourceAsStream. Hope this helps someone else too.
try this:
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
public class JsonParsing {
public static void main(String[] args) throws Exception {
InputStream is =
JsonParsing.class.getResourceAsStream( "sample-json.txt");
String jsonTxt = IOUtils.toString( is );
JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
double coolness = json.getDouble( "coolness" );
int altitude = json.getInt( "altitude" );
JSONObject pilot = json.getJSONObject("pilot");
String firstName = pilot.getString("firstName");
String lastName = pilot.getString("lastName");
System.out.println( "Coolness: " + coolness );
System.out.println( "Altitude: " + altitude );
System.out.println( "Pilot: " + lastName );
}
}
and this is your sample-json.txt , should be in json format
{
'foo':'bar',
'coolness':2.0,
'altitude':39000,
'pilot':
{
'firstName':'Buzz',
'lastName':'Aldrin'
},
'mission':'apollo 11'
}
With java 8 you can try this:
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class JSONUtil {
public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {
String content = new String(Files.readAllBytes(Paths.get(filename)));
return new JSONObject(content);
}
public static void main(String[] args) throws IOException, JSONException {
String filename = "path/to/file/abc.json";
JSONObject jsonObject = parseJSONFile(filename);
//do anything you want with jsonObject
}
}
Another way of doing the same could be using the Gson Class
String filename = "path/to/file/abc.json";
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
SampleClass data = gson.fromJson(reader, SampleClass.class);
This will give an object obtained after parsing the json string to work with.
On Google'e Gson library, for having a JsonObject, or more abstract a JsonElement:
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
JsonElement json = JsonParser.parseReader( new InputStreamReader(new FileInputStream("/someDir/someFile.json"), "UTF-8") );
This is not demanding a given Object structure for receiving/reading the json string.
Edit 2021-May-13:
As I commented myself: This solution does not properly take care of closing streams!
This does:
JsonElement json = null;
try (Reader reader = new InputStreamReader(new FileInputStream("/someDir/someFile.json"), "UTF-8")) {
json = JsonParser.parseReader( reader );
} catch (Exception e) {
// do something
}
As one can see the code gets bloated when doing correctly. I would clean-code move the 'loading of a json from a file' into a FileUtils.class; which probably already exists and does super nice adjustable Exception handling...
Example of json which I am using:
"identity" : {
"presentProvince" : [ {
"language" : "eng",
"value" : "China"
} ],
"presentAddressLine1" : [ {
"language" : "eng",
"value" : "bjbjbhjbhj"
} ],
"permanentAddressLine4" : [ {
"language" : "eng",
"value" : "123456"
} ]
} }
Here is the code to access language and value:
public static void JsonObjParsing() throws Exception {
File f = new File("id.json");
if (f.exists()){
InputStream is = new FileInputStream(f);
String jsonTxt = IOUtils.toString(is, "UTF-8");
System.out.println(jsonTxt);
JSONObject json = new JSONObject(jsonTxt);
JSONObject identity = json.getJSONObject("identity");
JSONArray identityitems = identity.getJSONArray("presentProvince");
for (Object o : identityitems) {
JSONObject jsonLineItem = (JSONObject) o;
String language = jsonLineItem.getString("language");
String value = jsonLineItem.getString("value");
System.out.println(language +" " + value);
}
}
}
public static void main(String[] args) throws Exception {
JsonObjParsing();
}
A way of getting both array of json in file or simply json would be
InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, Employee.class);
List<Employee> lstEmployees = mapper.readValue(inputStream, collectionType);
The file.json needs to be placed in the resources folder. If your file only has a json block without json array square brackets [] , you can skip the CollectionType
InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
Employee employee = mapper.readValue(inputStream, Employee.class);
Also refer here for original answer from where I have drawn.
import org.springframework.transaction.annotation.Transactional;
import org.springframework.core.io.ByteArrayResource;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.File;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.minidev.json.JSONObject;
String filename = "xyz.json";
#Transactional
public Object getFileInternalJsonData(String filename) {
try {
ByteArrayResource inputStream = new ByteArrayResource(Files.readAllBytes(Paths.get("D:\MyData\test\" + File.separator + filename)));
return new ObjectMapper().readValue(inputStream.getInputStream(), Object.class);
} catch (Exception e) {
return new JSONObject().appendField("error", e.getMessage());
}
}
You can try the below code, the main advantage for this code is you don't need to use any external dependency like org.json.simple
String resourceName = "response.json";
//InputStream is = JSONMapperImpl.class.getResourceAsStream(resourceName);
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream resourceStream = loader.getResourceAsStream(resourceName);
if (resourceStream == null) {
throw new NullPointerException("Cannot find resource file " + resourceName);
}
JSONTokener tokenizer = new JSONTokener(resourceStream);
JSONObject object = new JSONObject(tokenizer);
If you are facing any dependency issue then please add below dependency in your pom.xml file
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220924</version>
</dependency>

Categories

Resources