I have a JSON file and i am trying to deal with but the following error is appears:
Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.JSONObject.(JSONObject.java:195)
at org.json.JSONObject.(JSONObject.java:319)
at amazondataset.AmazonDataset.main(AmazonDataset.java:11)
Java Result: 1
This is a sample of the file:
{ "reviewerID": "A2SUAM1J3GNN3B",
"asin": "0000013714",
"reviewerName": "J. McDonald",
"helpful": [2, 3],
"reviewText": "I bought this for my husband who plays the piano. He is having a wonderful time playing these old hymns. The music is at times hard to read because we think the book was published for singing from more than playing from. Great purchase though!",
"overall": 5.0,
"summary": "Heavenly Highway Hymns",
"unixReviewTime": 1252800000,
"reviewTime": "09 13, 2009"
}
and this is my code, simply:
JSONObject ar = new JSONObject("E:\\amazonDS.json");
for (int i = 0; i < ar.length(); i++) {
System.out.println( "Name: " + ar.getString("reviewerName").toString() );
}
You have to read the content of the file first, because the constructor of JSONArray needs the file-content and not the file-path.
new JSONObject(new JSONTokener(new FileInputStream(new File("path"), "UTF-8")));
new JSONObject(new JSONTokener(new FileReader("path")));
update
You should use a filereader or specify the charset for the FileInputStream
Related
This question already has an answer here:
Expected BEGIN_ARRAY but was STRING but JSON is correct
(1 answer)
Closed 1 year ago.
I have the following problem. I have a Writer class which writes me all objects I create into a JSON file via Gson. The output looks like that:
{
"eventID": 1,
"title": "one",
"timeCreated": "Sep 23, 2007, 10:10:00 AM",
"timeModified": "Sep 23, 2007, 10:10:00 AM",
"timeStart": "Nov 11, 2999, 11:11:00 AM",
"timeEnd": "Nov 11, 3999, 11:11:00 AM",
"alarmOn": true,
"content": ""
}
eventID is a serialized integer created with AtomicInteger each time a new obj get created.
I want to manipulate those object e.g., set a new title.
So in the first step I tried to get the JSON back into java via fromJson
Gson gson = new Gson();
Type myDataType = new TypeToken<Collection<Event>>() {
}.getType();
Collection<Event> myData = gson.fromJson("awesome.json", myDataType);
for (Event e : myData) {
System.out.println("value= " + e.getTitle());
}
However, this leads to an error
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
How do I properly read my json back to my java class, apply some changes and write it after back again to json?
Let's look at the error code
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
So, it seems that the library is expecting a json array, but you give it a String instead.
It most probably has to do with this like new TypeToken<Collection<Event>>() you are saying that your type is a collection of events, not a single event.
Try changing it to TypeToken<Event> and see if this works.
I would like to be able to parse a JSON file that is structured something like:
[
{
"id": 1,
"name": {
"first": "name",
"secound": "name",
"last": "name"
},
"skills": [
"python",
"javascript"
],
"otherInfo": {
"something": 45,
"something2": 49
}
},
{
"id": 2,
"name": {
"first": "name",
"secound": "name",
"last": "name"
},
"skills": [
"python",
"javascript"
],
"otherInfo": {
"something": 45,
"something2": 49
}
}
etc...
]
into something looking like
array(
[0] => array(
0 => "id"
1 => "firstname"
2 => "otherData"
),
[1] => array(
0 => "id"
1 => "firstname"
2 => "otherData"
),
etc...
)
I'm pretty sure i have an idea on how to convert it into the format I want, but im having trouble actually reading the data from the file.
The two major issues im having:
Reading it from inside the jar.
Most of the examples used json.simple, and the json library i'm using doesn't seem to have that.
I tried some examples online, and a couple of the answers on this post
but no luck the biggest issue is that all of them are giving examples for reading an external file, while I'm trying to read one that is packaged inside the jar.
My project tree:
MyProject
L src
L myPackage
L MyClass.java
L MyJsonFile.json
The closest thing that I'm guessing almost worked is this (from the link above):
import org.json.JSONArray;
//code
JSONArray myJSONArray = new JSONArray(Main.class.getResourceAsStream("myFile.json"));
But that only seems to throw an error:
org.json.JSONException: JSONArray initial value should be a string or collection or array.
Thanks in advance!
The problem is org.json.JSONArray will only accept String,Collection or Array but you are trying to pass the InputStream object. which is what error messages also says
org.json.JSONException: JSONArray initial value should be a string or collection or array
So first convert the InputStream into String
InputStream inputStream = Main.class.getResourceAsStream("myFile.json");
InputStreamReader isReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(isReader);
StringBuffer sb = new StringBuffer();
String str;
while((str = reader.readLine())!= null){
sb.append(str);
}
And then convert it into JSONArray
JSONArray myJSONArray = new JSONArray(sb.toString());
After here you can iterate the JSONArray using for loop, like here
This question already has an answer here:
org.json.JSONException: JSONObject["address"] is not a JSONArray
(1 answer)
Closed 5 years ago.
Using this code to call steam api. Parsing json gives me some problems. I manage to print the json in the console, accessing furhter data fails. Here is my code:
JSONObject json = new JSONObject(IOUtils.toString(new URL("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXX&steamids=XXXXXXX"), Charset.forName("UTF-8")));
System.out.println(json.get("response")); >>> (1)
int out = json.getJSONObject("players").getInt("steamid");
System.out.println(out);
Exception in thread "main" org.json.JSONException: JSONObject["players"] not found.
{
"response": {
"players": [
{
"steamid": "XXXXX",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "XXXXX",
"lastlogoff": 123123,
"profileurl": "http://steamcommunity.com/id/XXX/",
"avatar": "XXXXX",
"avatarmedium": "XXXX",
"avatarfull": "XXXXX",
"personastate": 1,
"primaryclanid": "XXX",
"timecreated": XXX,
"personastateflags": 0,
"gameextrainfo": "Tom Clancy's Rainbow Six Siege",
"gameid": "359550"
}
]
}
}
You just need to understand the difference between JSONObject structure and JSONArray structure
The JSONObject will starts with "{", and JSONArray starts with "[".
I just noticed your mistake, you didnt assign json.get("response") to any variable.
JSONObject json = new JSONObject(IOUtils.toString(new URL("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXX&steamids=XXXXXXX"), Charset.forName("UTF-8")));
System.out.println(json.get("response"));
JSONObject playersJson=json.get("response");
int out = playersJson.getJSONArray("players").getJSONObject(0).getInt("steamid");
So try changing your code as above.
Your problem is that players is not a JSONObject, it's a JSONArray which contains JSONObjects. In this case, players contains one JSONObject, so you need to access that object first using players[0]:
int out = json.getJSONArray("players")[0].getInt("steamid");
Iam parsing a json using org.json in java . My json list like:
[ {
"id": "f187b01b145c4171b66d4a2ecabb8f44"
},
{
"id": "a5e66b7462e24924a03e89f0619a2398"
},
{
"id": "2fb3627360db4ab78a0b3f27527b1983"
} ]
I fetch data from the java code :
JSONObject json = new JSONObject(response.getEntity(String.class));
Jobs[] obj = new Gson().fromJson(json.toString(), Jobs[].class);
System.out.println(obj.toString());
But it gives an exception :
Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.JSONObject.<init>(JSONObject.java:197)
at org.json.JSONObject.<init>(JSONObject.java:324)
at br.usp.icmc.teste.ConnectionRestClient.getSaucelabsGetJobs(ConnectionRestClient.java:80)
at br.usp.icmc.teste.TestePrincipal.main(TestePrincipal.java:9)
why it did not recognized as JSONArray ? Where am I wrong ?
U can try with below code. There are many ways to do it, below is one of the way
JSONArray jsonArray = new JSONArray(response.getEntity(String.class));
for(int i =0; i< jsonArray.length(); i++){
if(jsonArray.get(i) instanceof JSONObject){
JSONObject jsnObj = (JSONObject)jsonArray.get(i);
String finalValue = (String)jsnObj.get("id");
}
}
My JSON is something like this:
[{
"myviews":[{
"2011-05-12_2011-05-14":{
"name":"thiswk",
"data":[[12,
2403
],
[13,
2082
],
[14,
5823
]
]
}
},
{
"2011-06-05_2011-06-7":{
"name":"lastwk",
"data":[[5,
1279
],
[6,
6685
],
[7,
2163
]
]
}
}
]
}
]
JSONObject jo = new JSONObject(jsonString);
JSONArray ja;
jo = jo.getJSONObject("2011-05-12_2011-05-14");
ja = jo.getJSONArray("data");
int resultCount = ja.length();
for (int i = 0; i < resultCount; i++)
{
JSONObject resultObject = ja.getJSONObject(i);
resultObject.getJSONArray("12");
System.out.println("--");
}
I am unable to read the values under the "data" array. Get this error
Exception in thread "main"
org.json.JSONException: A JSONObject
text must begin with '{' at character
1
You're trying to create a JSONObject based on a string that doesn't represent an object, but an array containing one object.
To get the contained object, try
JSONArray inputArray = new JSONArray(jsonString);
JSONObject jo = inputArray.getJSONObject(0);
I think some of your later work is wrong as well, but perhaps this will get you started.
data appears to be an array of arrays. Perhaps you need to call ja.getJSONArray(i)?