I know lot of people asked similars questions but, hell I'm stuck and I don't understand why. That's weird because the JSON is valid on jsonlint :
{
"Name": "Geography",
"Questions": [{
"_question": "Where is Max?",
"_answers": ["France", "USA", "Spain", "Tunisia"],
"_correctOne": 2,
"Asked": false,
"ID": 0
}, {
"_question": "Where is the Eiffel Tower?",
"_answers": ["Marseilles", "Le Mans", "Paris", "Lyon"],
"_correctOne": 3,
"Asked": false,
"ID": 1
}, {
"_question": "Where is Barcelona?",
"_answers": ["Italy", "Germany", "Portugual", "Spain"],
"_correctOne": 4,
"Asked": false,
"ID": 2
}, {
"_question": "Where is Malibu point?",
"_answers": ["San Francisco", "San Diego", "Los Angeles", "It\u0027s just in a movie"],
"_correctOne": 3,
"Asked": false,
"ID": 3
}, {
"_question": "Where takes place the famous 24h of Le Mans?",
"_answers": ["France", "Belgium", "Canada", "Martinique"],
"_correctOne": 1,
"Asked": false,
"ID": 4
}, {
"_question": "Which one of the following countries is the biggest one?",
"_answers": ["Mexico", "USA", "Russia", "India"],
"_correctOne": 3,
"Asked": false,
"ID": 5
}, {
"_question": "Where can you find a Camel?",
"_answers": ["Siberia", "Antartic", "Artic", "Sahara"],
"_correctOne": 4,
"Asked": false,
"ID": 6
}, {
"_question": "Where can\u0027t you find the statue of the liberty?",
"_answers": ["New York", "Paris", "Las Vegas", "Strasbourg"],
"_correctOne": 2,
"Asked": false,
"ID": 7
}, {
"_question": "What did Christophe Colomb has discovered?",
"_answers": ["Europe", "America", "Africa", "Asia"],
"_correctOne": 2,
"Asked": false,
"ID": 8
}, {
"_question": "Where can\u0027t you practice sky?",
"_answers": ["Maroco", "Canada", "Norway", "Dubaï"],
"_correctOne": 1,
"Asked": false,
"ID": 9
}, {
"_question": "Which one of the following countries isn\u0027t a neighboor of the France?",
"_answers": ["Germany", "Italy", "Spain", "Portugual"],
"_correctOne": 4,
"Asked": false,
"ID": 10
}]
}
So, it's just an ArrayList<Category>. Category is the following class:
public class Category {
public String Name;
public ArrayList<Question> Questions;
}
Also, the Question class below:
public class Question {
private String _question;
private String[] _answers;
private int _correctOne;
public boolean Asked;
public int ID;
}
Everything seems alright to me, I checked again and again, still have this error. However, something seems weird, each ' is replaced by \u0027, but it doesn't seems to be the problem..
I'm parsing the Gson from the following function:
public static boolean ReadCategoryFileTxt(Category category) {
try {
File file = new File(category.Name + ".txt");
Scanner sc = new Scanner(file);
String JSONString = "";
while (sc.hasNextLine())
JSONString += sc.nextLine();
Gson gson = new Gson();
Category _category = gson.fromJson(JSONString, Category.class);
category.Name = _category.Name;
category.Questions = _category.Questions;
//Debug.Println(gson.toJson(category, Category.class));
sc.close();
}
catch (Exception e)
{
Debug.PrintException(e);
return (false);
}
return (true);
}
Any idea for this "Expected BEGIN_OBJECT but was STRING at line 1 column 4"?
Thank in advance !
Looks the start of the JSON read from file is not open flower braces {
Point 1 - See if the file has any incorrect start characters
Point 2 - Set your text file encoding to UTF -8
Point 3 - Use String Builder instead of using + append assignment
Point 4 - If you have notepad++, you shall remove non-ascii characters using - Notepad++, How to remove all non ascii characters with regex?
public static boolean ReadCategoryFileTxt(Category category) {
try {
File file = new File(category.Name + ".txt");
Scanner sc = new Scanner(file);
StringBuilder JSONString = new StringBuilder;
while (sc.hasNextLine())
JSONString = JSONString.append(sc.nextLine());
Gson gson = new Gson();
Category _category = gson.fromJson(JSONString.toString().trim(), Category.class);
category.Name = _category.Name;
category.Questions = _category.Questions;
//Debug.Println(gson.toJson(category, Category.class));
sc.close();
}
catch (Exception e)
{
Debug.PrintException(e);
return (false);
}
return (true);
}
I'd like to leave a few words based on what you clarified in the comments. To be honest, I could not reproduce the exact exception with ... line 1 column 4 having ... line 1 column 1 instead, regardless the default JVM file.encoding property, but you're faced with a classic file encoding issue.
Your JSON is really well-formed.
Java promotes some naming conventions so _question and Asked appearing in the JSON can be expressed as #SerializedName("_question") String question; and #SerializedName("Asked") boolean isAsked; respectively.
\u0027 is an escaped character of '. Characters can be unescaped if they are a part of the enclosing document encoding. The apostrophe fits ASCII just perfect, however it may be escaped in order not to break JSON documents syntactically, say, string literals in JSON strings.
The real problem was that your JSON file was not invalid characters per se, but an UTF-8 encoded file with an explicit Byte Order Mark that should be processed before parsing begins to make sure that file content encoding is detected and decoded fine ( literally stands for UTF-8). UTF-aware editors just do not show BOMs since the latter are not considered bad or illegal characters, but use them to deal with UTF-encoded files (file encoding names are usually shown in statusbars, etc). That's why copying/pasting worked for you: BOMs were not included to copies (they "live" in files only, and in clipboard metadata I guess). By default, Java classes do not make any assumptions on the incoming file encoding leaving the decision on it on your own or even on user's own. It is described here. Therefore Gson should not process it and Gson really does not do it. All Gson can only consume is JSON tokens streams (and that's perfect design), so you have either to detect the input encoding, or let your user specify it.
You don't need to accumulate an intermediate String to parse a JSON: this is just memory wasting especially for big JSON documents. Gson can work in streaming manner, so it accepts Reader instances in order not to accumulate intermediate JSON strings reading a given input stream token by token trying to consume as less memory as possible. Also note that reading line by line is cheaper with BufferedReader rather than Scanner, however it's still discouraged for you case.
If you're using Java 7 or later, use try-with-resources to make sure your I/O resources are not leaked (otherwise use finally to make sure there are no resource leaks). Also it's worth noting that instantiating a Gson instance may be considered a little expensive operation, and since Gson instances are thread-safe and immutable, they can be instantiated once per application and shared globally (not necessarily a public static final Gson ..., of course, but something encapsulated elsewhere in a good design solution).
try( final Reader reader = new InputStreamReader(new FileInputStream(new File(category.Name + ".txt")), StandardCharsets.UTF_8)) {
Category _category = gson.fromJson(reader, Category.class);
category.Name = _category.Name;
category.Questions = _category.Questions;
//Debug.Println(gson.toJson(category, Category.class));
} catch ( Exception e ) {
Debug.PrintException(e);
return (false);
}
return (true);
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I am currently using bufferreader to read an API documentation. Below is part of the output:
"number": 88,
"results": [
{
"time": "2013-04-15T18:05:02",
"name": "..."
},
{
"time": "2013-05-01T18:05:00",
"name": "..."
},
...
]
If I want to extract only "2013-04-15T18:05:02", which is the date. How can I do that?
You can use minimal json.
The following snippet extracts the dates and id's of all items:
JsonObject object = Json.parse(output).asObject();
JsonArray results = object.get("results").asArray();
for (JsonValue item : results) {
String date = item.asObject().getString("date", "");
String id = item.asObject().getString("id", "");
...
}
The format of your string seems to be JSON. You can use Jackson API to parse the JSON string into an array. If you don't want to use Jackson or other JSON API, you can still do it using some of the java.util.String class methods. Checkout the following sample:
List<String> dates = new ArrayList<String>();
String results = jsonString.substring(jsonString.indexOf("results"));
while((int index = results.indexOf("\\"date\\"")) != -1) {
String date = results.substring(results.indexOf(':', index), results.indexOf(',', index)).replaceAll(" ", "").replaceAll("\\"", "");
dates.add(date);
results = results.substring(results.indexOf(',', index));
}
This question already has answers here:
Parsing JSON Array within JSON Object
(5 answers)
Closed 6 years ago.
Apologies, I have tried multiple things here and seem to run into some issues. This should be simple.
JSON file :
{
"content": [
{
"media_type": "text/html",
"text": "<p>Hello world</p>"
},
{
"media_type": "text/plain",
"text": "Hello world"
}
],
"id": "123",
"title": "no-title"
}
I have a JSONObject created from this string.
I have tried -
String txtFromJSON = json.getJSONObject("content").getJSONObject("text").toString();
String txtFromJSON = json.getString("content.text");
String txtFromJSON = json.getString("content");
All of these fail.
The output I would like is simply the
<p>Hello world<p>
from the first text field.
Is there any simple way for me to get this data stored in a variable?
Thanks.
try this:
final JSONObject obj = new JSONObject(youJsonString);
final JSONObject content = obj.getJSONArray("content");
final int n = content.length();
if(n ==1 ){
String txtFromJSON = json.getString("text");
}
I am trying to extract the "first_name" and "last_name" from a long string of information that look like this:
{
"123123123": {
"id": "12321312****",
"email": "***************",
"first_name": "Marcus",
"gender": "male",
"last_name": "Bengtsson",
"link": "https://www.facebook.com/app_scoped_user_id/123123123/",
"locale": "en_EN",
"middle_name": "Peter",
"name": "Marcus Peter Bengtsson"
}
}
The way I do it (which is probably horribly wrong and a pretty bad solution) is that I firstly extract the substring from "first_name" to "link" with this code:
String subStr = str.substring(str.indexOf("first_name"), str.lastIndexOf("link"));
Then I get:
first_name":"Marcus","gender":"male","last_name":"Bengtsson","
Then I do the same thing but from ":" to "gender" to get the "first_name:
String firstNameOfUser = subStr.substring(subStr.indexOf(":")+2, subStr.lastIndexOf("gender")-3);
Then the same thing for "last_name":
String lastNameOfUser = subStr.substring(subStr.indexOf(""last_name"")+12, subStr.lastIndexOf(",")-1);
And lastly I append the both strings with a space in between:
String nameOfUser = new StringBuilder().append(firstNameOfUser).append(" ").append(lastNameOfUser).toString();
And then I get:
Marcus Bengtsson
There is probably a much better way to do this but I can't seam to figure out how.
This looks like a JSON so it would be much better to parse it as such using one of many available parsers and then extract the data.
The given String is a JSON, use the JSONParser to parse it to json and then extract the data needed.
thats a json? visit this link JSON Example
nameOfUser = 123123123.first_name + " " + 123123123.last_name;
i hope this will help you
As #Crozin wrote it looks like json but if you can't parse it in this way you can always use regex. Just use Matcher, Pattern with a regex ^.*\"first_name\":\"([a-zA-Z]+)\".*\"last_name\":\"([a-zA-Z]+)\".*$.
So this is my sample Json Text,
{
"Date": [
1545,
"20 January 2014"
],
"docText": "ABCD",
"docSource": "",
"docID": 99,
"docDate": "",
"Date": [
1930,
"1995/11",
"past decade",
"today",
"Today"
],
"docText": "JJJJJJJ\"",
"Organization": [
"x",
"y",
"z"
],
"docSource": "",
"docID": 98,
"docDate": "",
"Person": "xxxxxx"
}
Now I need a Java code to Read from this file and Display all the docText, docID Entities. I'm able to retrieve only one Entity.
This is the part of the code im using.
JSONParser jsonParser = new JSONParser();
try {
FileReader fileReader = new FileReader(jsonFilePath);
JSONObject jsonObject = (JSONObject) jsonParser.parse(fileReader);
String docid = (String) jsonObject.get("docText");
System.out.println("DocText: " +docid);
long members = (long) jsonObject.get("docID");
System.out.println("docID: " + members);
JSONArray names = (JSONArray) jsonObject.get("Organization");
Iterator i = names.iterator();
while (i.hasNext()) {
System.out.println("Organization: "+i.next());
I really need this working soon! Thank you
The JSON file has duplicate keys so you probably can't read them all using a standard parser.
From http://www.ietf.org/rfc/rfc4627.txt:
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.
Instead, I'd expect each entity to be a separate object within an array.
AFAIK there is no option to fetch multiple values from a JSON object in a single get...