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
}
]
}
Related
Hello i have a json file with data exists like this
[
{
"employee": {
"firstName": "Rudi",
"lastName": "Anton"
}
},
{
"employee": {
"firstName": "Syafira",
"lastName": "Zarakaria"
}
}
]
I want to append json data to this file.
My code now not appending data, re-write file.
Help me
This is my code
JSONObject employeeDetails = new JSONObject();
employeeDetails.put("firstName", "Justin");
employeeDetails.put("lastName", "Saklitinov");
JSONObject employeeObject = new JSONObject();
employeeObject.put("employee", employeeDetails);
JSONObject employeeDetails2 = new JSONObject();
employeeDetails2.put("firstName", "Zara");
employeeDetails2.put("lastName", "Lovez");
JSONObject employeeObject2 = new JSONObject();
employeeObject2.put("employee", employeeDetails2);
//Add employees to list
JSONArray employeeList = new JSONArray();
employeeList.add(employeeObject);
employeeList.add(employeeObject2);
//Write JSON file
try{
String strPath = "employee.json";
File strFile = new File(strPath);
boolean fileCreated = strFile.createNewFile();
//File appending
Writer objWriter = new BufferedWriter(new FileWriter(strFile));
//objWriter.write(employeeList.toJSONString());
objWriter.flush();
objWriter.close();
out.flush();
out.print("OK");
} catch (IOException e) {
e.printStackTrace();
}
You should read the json file into an JSONArray. Add new employee data to this JSONArray and write it to the file. I have modified some of your code.
// Read json file
String jsonFileStr = new String(
Files.readAllBytes(Paths
.get("PATH TO YOUR EMPLOYEE JSON")),
StandardCharsets.UTF_8);
System.out.println(jsonFileStr);
JSONArray jsonArray = (JSONArray) new JSONParser().parse(jsonFileStr);
// Create employee data to be add to json file
JSONObject employeeDetails = new JSONObject();
employeeDetails.put("firstName", "Justin");
employeeDetails.put("lastName", "Saklitinov");
JSONObject employeeObject = new JSONObject();
employeeObject.put("employee", employeeDetails);
JSONObject employeeDetails2 = new JSONObject();
employeeDetails2.put("firstName", "Zara");
employeeDetails2.put("lastName", "Lovez");
JSONObject employeeObject2 = new JSONObject();
employeeObject2.put("employee", employeeDetails2);
// Add data to jsonArray read from json file
jsonArray.put(employeeObject);
jsonArray.put(employeeObject2);
// Writing the jsonArray back to file
String strPath = "PATH TO EMPLOYEE JSON";
File strFile = new File(strPath);
boolean fileCreated = strFile.createNewFile();
Writer objWriter = new BufferedWriter(new FileWriter(strFile));
objWriter.write(jsonArray.toString());
objWriter.flush();
objWriter.close();
Note: You might want to reconsider using the same key 'employee' multiple times in the json.
Try BufferedWriter it open a file in append mode.
BufferedWriter out = new BufferedWriter(
new FileWriter(fileName, true));
out.write(str);
out.close();
yes if you are reading as object and writing as on object. It is a overwrite on the same file.
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.
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'm trying to parse a JSON response
it's structure is:
{
"metric": {
"name": "string",
"values": [
"string"
]
}
}
My code so far:
StringBuilder sb = new StringBuilder();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
wr.close();
reader.close();
JSONObject json = new JSONObject(sb.toString());
JSONArray jsonArray = json.getJSONArray("values");
List<String> list = new ArrayList<>();
String errorPercent ="";
for(int i = 0 ; i < json.length() ; i++){
errorPercent = jsonArray.getJSONArray(i).getString(i);
list.add(errorPercent);
}
The output I'm getting is saying that "values " was not found,
am I misunderstanding the structure of the JSON response?
Edit
It appears the structure I was given on the site I'm receiving the response from is not correct. it appears to be a more complicated structure
I have modified my code accordingly:
JSONObject json = new JSONObject(sb.toString());
JSONObject metricsData = json.getJSONObject("metric_data");
JSONArray metrics = metricsData.getJSONArray("metrics");
System.out.println(metrics.toString());
The print out is as follows:
[{"timeslices":[{"values":{"max_response_time":0,"calls_per_minute":0,"average_be_response_time":0,"error_percentage":0,"min_response_time":0,"requests_per_minute":0,"average_network_time":0,"average_response_time":0,"average_fe_response_time":0,"total_app_time":0,"call_count":0,"fe_time_percentage":0,"total_network_time":0,"total_fe_time":0,"network_time_percentage":0},"from":"2015-10-25T22:39:00+00:00","to":"2015-10-25T22:40:00+00:00"},{"values":{"max_response_time":0,"calls_per_minute":0,"average_be_response_time":0,"error_percentage":0,"min_response_time":0,"requests_per_minute":0,"average_network_time":0,"average_response_time":0,"average_fe_response_time":0,"total_app_time":0,"call_count":0,"fe_time_percentage":0,"total_network_time":0,"total_fe_time":0,"network_time_percentage":0},
There appears to be another array within the array: "timeslices" is that right? how do I get at that array?
I unsuccessfully tried:
JSONArray timeslices = metrics.getJSONArray("timeslices");
values is a field inside metric.
You'd need to first get the metric object, then look inside that for values.
JSONObject metric = json.getJSONObject("metric");
JSONArray jsonArray = metric.getJSONArray("values");
My String array has the following output each time it iterates through the loop
apple
orange
I want to convert my string array output to json format/jsonarray. I tried but it gives output as
{"fruits",apple}
{"fruits",orange}
I want my output as
{"fruits": [
{
"1": "apple"
}
{
"2": "orange"
}
I tried the below code
String[] strArray = new String[] {newString};
JSONObject json=new JSONObject();
//json.put("fruits", newString);
//System.out.println(json);
for(int i=0;i<strArray.length;i++)
{
System.out.print(strArray[i]+"\t");
json.put("",strArray[i]);
}
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
for(int i=0;i<strArray.length;i++)
{
JSONObject fruit = new JSONObject();
fruit.put(""+i,strArray[i]);
array.put(fruit);
}
obj.put("Fruits",array);
System.Out.Println(obj.toString(2));
Try below code :-
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("key", "value");
String jsonString = jsonObject.toString();
I hope this will work for you.