How do I read from JSON File in Java? [duplicate] - java

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I've read some other questions about this, but they did not seem to help me.
As the title says, I want to know how to read from .json files using Java.
Eg. I want my program to read a boolean value. (That is what I want it to.)
I really hope you will be able to help me with this. I am able to use json-simple-1.1.1 if needed.
What I've found so far (That did not work):
String str = "Name";
JSONObject obj = new JSONObject();
String n = (String) obj.get("Name");
if (!n.equals("true")) {
} else
if (n.equals("true")) {
ButtonsShow = true;
} else if (n.equals("false")) {
ButtonsShow = false;
}
Click to view the .Json file

you try it:
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 JsonSimpleExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\test.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
long age = (Long) jsonObject.get("age");
System.out.println(age);
// loop array
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}

Related

A space in JSON value causes "unexpected token END OF FILE at position 11" exception when parsing in Java

When I use the parser from org.json.simple.parser.* I get an exception whenever one of the values in JSON contains a space. For example:
{"name":"Adam"}
would parse correctly, but
{"name":"Ad am"}
would cause "unexpected token END OF FILE at position 11" exception
Here is the code that I use to convert a JSON string into a JSONObject.
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringJSON);
Try to get through this below example and each value contains space except integer one and giving this example just because of you don't have shared your source code.
JSON File(personal_detail.json):
{
"name":"arif mustafa",
"age":26,
"address":["district is Korba","state is Chhattisgarh","country is India"]
}
Java source to read the JSON file format:
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 JSONExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("src/resources/personal_detail.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject + "\n");
String name = (String) jsonObject.get("name");
System.out.println("name : " + name);
long age = (Long) jsonObject.get("age");
System.out.println("age : " + age);
//get Object loop array
JSONArray address = (JSONArray) jsonObject.get("address");
System.out.println("address is : ");
Iterator<String> iterator = address.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}

Splitting String into object fields

I looking for best aproach for this problem.
String example:
{"id":16,"title":"title1","description":"Quote \"foo\" asdf","execution_time":"2017-04-26 06:15:00"}
I need to create new object with gets fields values from the string. What is correct way to do it? Creating constructor and pass this string as parameter and use stringtokenizer inside it? Or maybe using Pattern would be better?
(I am going to correct the code)
I am proposing to use org.json.simple.*. In my opinion, it will be easy, for example:
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJson1 {
public static void main(String[] args) {
String url = "....";
/*
* {"id":16,"title":"title1","description":"Quote \"foo\" asdf","execution_time":"2017-04-26 06:15:00"}
*/
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
// get the title
System.out.println(genreJsonObject.get("title"));
// get the data
JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("genre_title"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}

error: non-static method get(Object) cannot be referenced from a static context

The code below shows:
JavaApplication1.java:34: error: non-static method get(Object) cannot be referenced from a static context
JSONArray cars = (JSONArray) JSONObject.get("cars");
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 JavaApplication1 {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("C:/Users/Glambert/Dropbox/java/New folder/perfection/UPdate/json.txt"));
for (Object o : a)
{
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
JSONArray cars = (JSONArray) JSONObject.get("cars");
for (Object c : cars)
{
System.out.println(c+"");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Anyone has any idea why this is the case?
(by the way, this code was found online and I edited it to test run, so that I can create a new code to take in a different kind of txt file.)
Project: Code from StackOverflow page How to read json file into java with simple JSON library
Code Author: https://stackoverflow.com/users/1212960/greg-kopff
Check this line
JSONArray cars = (JSONArray) JSONObject.get("cars");
change it with
JSONArray cars = (JSONArray) person.get("cars");
Issue was since you are calling the get method directly on the class.

How to parse large local JSON file to retrieve player names and more with an array

I have a large stream of data that I can capture from a game that I play using CharlesProxy. I'd like to parse the data and have it print out (eventually build an excel spreadsheet) the player names, x and y location, and the guild name.
The JSON data in Paste-Bin (you'll have to go down a few entries to see one of the results that actually returns a player name as well):
http://pastebin.com/v4kAaspn
Here's an example I found here that I tried to use to just return the player name, but I get a Null Pointer Exception error. Any advice will be greatly appreciated, thank you so much!
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 ToolMain {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(
"//Users//Brandon//Desktop//JSONData.JSON"));
JSONObject jsonObject = (JSONObject) obj;
//get responses
JSONArray rsp = (JSONArray)jsonObject.get("responses");
//System.out.println(rsp);
//get return value
JSONObject rtvalue = (JSONObject)rsp.get(0);
//System.out.println(rtvalue);
//get hexes object
JSONObject hexes = (JSONObject)rtvalue.get("return_value");
//System.out.println(hexes);
//get hexes array
JSONArray hexesArray = (JSONArray)hexes.get("hexes");
Iterator<JSONObject> iterator = hexesArray.iterator();
while (iterator.hasNext()) {
JSONObject factObj = iterator.next();
String playerName = (String) factObj.get("player_name");
if (playerName != null) {
System.out.println(playerName);
}
}
//System.out.println(hexesArray);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
The NullPointerException is happening on below line because your JSONArray msg is null:
Iterator<JSONObject> iterator = msg.iterator();
Apply a check if(msg is not null) before you create an iterator on it.
Try it this way:
JSONObject jsonObject = (JSONObject) obj;
//get responses
JSONArray rsp = (JSONArray)jsonObject.get("responses");
System.out.println(rsp);
//get return value
JSONObject rtvalue = (JSONObject)rsp.get(0);
System.out.println(rtvalue);
//get hexes object
JSONObject hexes = (JSONObject)rtvalue.get("return_value");
System.out.println(hexes);
//get hexes array
JSONArray hexesArray = (JSONArray)hexes.get("hexes");
System.out.println(hexesArray);

Accessing JSON property name using java

I'm working on a way to parse JSON files and collect their contents for use elsewhere. I currently have a working example that is as follows:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class testJSONParser {
public static void main(String[] args) throws Exception {
List<Map<String, String>> jsonArray = new ArrayList<Map<String, String>>();
BufferedReader br = new BufferedReader(new FileReader("json.txt"));
try {
String line = br.readLine();
while (line != null) {
JSONObject jsonObject = (JSONObject)new JSONParser().parse(line);
Map<String, String> currentLineMap = new HashMap<String, String>();
currentLineMap.put("country", jsonObject.get("country").toString());
currentLineMap.put("size", jsonObject.get("size").toString());
currentLineMap.put("capital", jsonObject.get("capital").toString());
jsonArray.add(currentLineMap);
line = br.readLine();
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
};
}
}
}
I'm using the json simple library for parsing the passed in JSON strings.
Here's a sample string from the parsed file.
{"**country**":"Canada","**size**":"9,564,380","**capital**":"Ottawa"}
What my question is about is how to take this code, and have the put method be able to assign to the corresponding Map dynamically. This is what I currently have:
for (int i = 0; i < jsonObject.size(); i++) {
currentLineMap.put(jsonObject.???.toString(), jsonObject.get(i).toString());
}
The ??? part is where I'm stumped. Getting the values of the current JSON line is easy enough. But how to get the property values (highlighted in bold in the JSON string sample) eludes me. Is there a method that I can call on this object that I'm not familiar with? A different and better way to itenerate through this? Or am I doing this completely assbackwards right from the get go?
In the JSON.org reference implementation, you could do:
for (String key : JSONObject.getNames(jsonObject))
{
map.put(key, jsonObject.get(key));
}
In JSON simple, you would do:
for (Object keyObject : jsonObject.keySet())
{
String key = (String)keyObject;
map.put(key, (String)jsonObject.get(key));
}
This should do the trick.

Categories