I haven't been programming for a long time but I like it and trying to get back on track. So please excuse the nature of the problem/question here.
What I need is pretty simple in my opinion but i'm mostly struggling with using gson and json-simple to read my json file, one at a time, and be able to retrieve the values.
I have seen many approaches on here but as I said been a while and I have not done Java a lot in my career. So need some guidance/explanation on the best approach.
JSON:
[{ "car": "Toyota", "colour": "red", "qty": "1","date_manufactured":"12972632260006" }, { "car": "Hyundai", "colour": "red", "qty": "2","date_manufactured":"1360421626000" }, { "car": "Kia", "colour": "blue", "qty": "2", "date_manufactured":"1265727226000"}, ]
Any help to put me on the right track is appreciated!
Create a POJO class to represent your JSON data:
public class CarInfo {
String car;
String colour;
String qty;
String date_manufactured;
}
Use GSON to parse JSON String Array
String carInfoJson = "[{ \"car\": \"Toyota\", \"colour\": \"red\",\"qty\": \"1\",\"date_manufactured\":\"12972632260006\" }, { \"car\":\"Hyundai\", \"colour\":\"red\",\"qty\":\"2\",\"date_manufactured\":\"1360421626000\" }]";
Gson gson = new Gson();
CarInfo[] carInfoArray = gson.fromJson(carInfoJson, CarInfo[].class);
Use GSON to parse JSON String Array from a file
String carInfoJson= new String(Files.readAllBytes(Paths.get("filename.txt")));
Gson gson = new Gson();
CarInfo[] carInfoArray = gson.fromJson(carInfoJson, CarInfo[].class);
Use GSON to parse JSON String Array from a file using BufferedReader
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
Gson gson = new Gson();
CarInfo[] carInfoArray = gson.fromJson(reader, CarInfo[].class);
} catch (FileNotFoundException ex) {
...
} finally {
...
}
Use GSON to parse JSON String Array from a file using JsonReader in stream mode
try {
InputStream stream = new FileInputStream("c:\\filename.txt");
JsonReader reader = new JsonReader(new InputStreamReader(stream, "UTF-8"));
Gson gson = new Gson();
// Read file in stream mode
reader.beginArray();
while (reader.hasNext()) {
CarInfo carInfo = gson.fromJson(reader, CarInfo.class);
}
reader.endArray();
reader.close();
} catch (UnsupportedEncodingException ex) {
...
} catch (IOException ex) {
...
}
I'm using json-simple to explain how to do this. Your json is a JSONArray (because it starts and ends with square brackets) with JSONObject (curly brackets with pair list) inside so first you've to extract the array using a JSONParser and then you can easily iterate over it and get fields from each JSONObject.
Here is a simple example it just shows you an easy and understandable way:
String json = "[{ \"car\": \"Toyota\", \"colour\": \"red\", \"qty\": \"1\",\"date_manufactured\":\"12972632260006\" }, { \"car\": \"Hyundai\", \"colour\": \"red\", \"qty\": \"2\",\"date_manufactured\":\"1360421626000\" }]";
JSONParser parser = new JSONParser();
try {
/* It's a JSONArray first. */
JSONArray tmpArr = (JSONArray)parser.parse(json);
for(Object obj : tmpArr){
/* Extract each JSONObject */
JSONObject tmpObj = (JSONObject) obj;
System.out.println(tmpObj.get("car"));
System.out.println(tmpObj.get("colour"));
System.out.println(tmpObj.get("qty"));
System.out.println(tmpObj.get("date_manufactured"));
}
} catch (ParseException e) {
e.printStackTrace();
}
Note that you can use Gson, it's much more complete then json-simple but a little bit trickier.
Related
I've written a file JSON with the information that I need to use to create an array
This is the json that I'm using
[{
"matr": [0,0],
"room": "b",
"door": true,
"respawnPoint": false
},
{
"matr": [0,1],
"room": "b",
"door": false,
"respawnPoint": false
},...
]
and this is how I try to de-serialize it with java
String path="src/main/resources/room.json";
JsonReader reader= new JsonReader(new FileReader(path));
SupportPosition[] a=new Gson().fromJson(path,
SupportPosition[].class);
but this error appears
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
You are passing the file path as a parameter into the Gson constructor.
You must pass the JsonReader object into the Gson constructor as a parameter.
JsonReader reader= new JsonReader(new FileReader(path));
SupportPosition[] a=new Gson().fromJson(reader, SupportPosition[].class);
try this and let me know.
Parsing JSON array into java.util.List with Gson I think your question has already been answered in a different post. Take a look into it.
public class Human {
String name;
Integer age;
//getters and setters
}
Main class is below :
public class Solution{
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
String json = "[{\"name\":\"Dummy\", \"age\":37}, {\"name\":\"Dummy2\", \"age\":38}]";
try {
// 1. convert JSON array to Array objects
Human[] HumanObjects = mapper.readValue(json, Human[].class);
System.out.println("JSON array to Array objects...");
for (Human Human : HumanObjects) {
System.out.println(Human);
}
// 2. convert JSON array to List of objects
List<Human> ppl2 = Arrays.asList(mapper.readValue(json, Human[].class));
System.out.println("\nJSON array to List of objects");
ppl2.stream().forEach(x -> System.out.println(x));
// 3. alternative
List<Human> pp3 = mapper.readValue(json, new TypeReference<List<Human>>() {});
System.out.println("\nAlternative...");
pp3.stream().forEach(x -> System.out.println(x));
} catch (Exceptoion e) {
e.printStackTrace();
}
}
}
Use need to import "Jackson". Probably add a Maven dependency. Let me know if it helps.
I'm trying to use JSON simple as part of a Java application to pull specific data from a .json file. Whenever I run the program, I get an unexpected token error message when it tries to parse.
A simplified version of the JSON file is as follows:
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"}
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
My code is as follows:
public static void readJSON() {
JSONParser jsonParser = new JSONParser();
try {
FileReader reader = new FileReader(fileLocation);
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray jsonArray = (JSONArray) jsonObject.get("");
Iterator<?> i = jsonArray.iterator();
while (i.hasNext()) {
JSONObject obj = (JSONObject) i.next();
int tweetID = (int) obj.get("id");
String lang = (String) obj.get("lang");
}
} catch (Exception e) {
e.printStackTrace();
}
}
In this example, the line of code:
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
throws an error due to an unexpected token at the first left brace ({) of the second JSON object (i.e, at the brace before "id":345).
How could I go about resolving this issue?
And, as a follow up, how would one also pull the information for the username in this example?
Thanks for taking the time to read through this, and for any assistance provided!
That file is an invalid JSON file, it contains an entire object on each line.
What you'll need to do is read the file line by line, and then passing each line to the parser to create a new object.
If you fix your code, you can solve unexpected token error.
public static void readJSON() {
JSONParser jsonParser = new JSONParser();
try {
FileReader reader = new FileReader(fileLocation);
//You need to fix this part
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
Iterator<?> i = jsonArray.iterator();
while (i.hasNext()) {
JSONObject obj = (JSONObject) i.next();
int tweetID = (int) obj.get("id");
String lang = (String) obj.get("lang");
}
} catch (Exception e) {
e.printStackTrace();
}
}
You are trying to parse JSON object, and you actually have two JSON objects.
And in your code you are actually expect an array of JSON objects.
So, use the proper JSON array:
[
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"},
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
]
In order to quickly check your JSON syntax, you can use some online tool.
Your JSON is indeed wrong. It actually contains 2 valid JSONs. If you want to create one valid JSON document you have to wrap your input with { and } or [ ] if this is an array or collection. Please note the comma that separates 2 different entities.
[
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"},
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
]
I want to read this json in a servlet
{
"text" : "ABC",
"msg" : "9551667858",
"all":[
{"name":"one"},
{"name":"two"}
],
"obj":{
"firstname":"John",
"lastname":"Doe"
}
}
Now i want to get this values to separately to string,jsonarray and json object
this is how i do that
PrintWriter out = response.getWriter();
try {
String newObj = request.getParameter("text");;
JSONObject jObj = new JSONObject(request.getParameter("obj"));
JSONArray jArray=new JSONArray(request.getParameter("all"));
out.print(newObj);
} catch (Exception e) {
e.printStackTrace();
out.write(e.toString());
}
response.setContentType("application/json");
your code is partially correct.String newObj = request.getParameter("jsondata"); is correct. Then you have to create the jObj from newObj string.
String jsonString = <your json String>
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject allObj = jsonObj.getJSONObject("obj");
JSONArray allArray = jsonObj.getJSONArray("all");
First read the data from request object :-
String jsonStr = request.getParameter("jsondata");
Use org.json library to parse it and create JsonObject :-
JSONObject jsonObj = new JSONObject(jsonStr );
Now, use this object to get your values :-
String id = jsonObj.getString("text");
You can see complete example here :-
How to parse Json in java
if your String data like ,
{
"text" : "ABC",
"msg" : "9551667858",
"all":[
{"name":"one"},
{"name":"two"}
],
"obj":{
"firstname":"John",
"lastname":"Doe"
}
}
and It can get like,
String jsonData = request.getParameter("jsondata");
Parse to JSONObject is.
JSONObject jsonObject = new JSONObject(jsonData); // put "String"
You can get JSONArray like,
JSONArray jsonArray = jsonObject.getJSONArray("all");
good luck
I have text file with JSON data in it with following format:
[ {
"belongs_to_suite": "no",
"belongs_to_suite_id": "",
"brand_family": "",
"cat_manufacturer_id": 4382,
"cat_sw_edition_id": null,
"cat_sw_product_id": 38,
"cat_sw_release_id": 47354894, } ]
I want to read only brand_family, for which I suppose I need a JSON array.
Do I need to define this format using JSON objects first?
I have downloaded org.json lib, and I have following code in which I am reading the text file, but I cannot find out how do I define format and then import all data in [{}...{}] into an array and:
FileInputStream fstream = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
try {
JSONObject obj = new JSONObject(br);
String n = obj.getString("version");
//int a = obj.getInt("age");
System.out.println(n);
}
As mentioned in the comments, your JSON is an array, so firstly you should call:
JSONArray array = new JSONArray(br);
Then you can do something with the size or get the first object:
JSONObject first = array.getJSONObject(0);
And finally, having the JSONObject, you can extract and process any field:
System.out.println(first.getString(""));
You can do it simply as below :
JSONParser parser=new JSONParser();
try {
JSONObject jsonObject = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("D://jsontest.txt")));
JSONArray lang= (JSONArray) jsonObject.get("obj");
for(int i=0; i<lang.size(); i++){
JSONObject obj=(JSONObject) lang.get(i);
System.out.println(obj.get("brand_family"));
}
}catch(Exception e){
e.printStackTrace();
}
Change your file to below :
{
"obj": [
{
"belongs_to_suite": "no",
"belongs_to_suite_id": "",
"brand_family": "1",
"cat_manufacturer_id": 4382,
"cat_sw_edition_id": null,
"cat_sw_product_id": 38,
"cat_sw_release_id": 47354894
},
{
"belongs_to_suite": "yes",
"belongs_to_suite_id": "",
"brand_family": "2",
"cat_manufacturer_id": 4382,
"cat_sw_edition_id": null,
"cat_sw_product_id": 38,
"cat_sw_release_id": 47354894
}
]
}
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 :)