This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 6 years ago.
I'm new bee working on passing below data from jquery to Servlet. Below are my files
javascript:
<script type="text/javascript">
function getData(tableName)
{
var tableId =tableName+"Table";
jsonObj = [];
$(\'#' + tableId + '\').find(\'tbody>tr\').each(function (i) {
var $tds = $(this).find('td'), setvilId = $tds.eq(1).text(),setvilNotes = $tds.eq(8).text();
item = {};
item["id"] = setvilId;
item["notes"] = setvilNotes;
jsonObj.push(item);
});
console.log(jsonObj);
var jsonString =JSON.stringify(jsonObj);
request(jsonString);
};
</script>
<script type=\"text/javascript\">
function updateNotes () {
var editable = true;
var editables = $('td[id*=notestd], td[id*=eta]');
editables.attr('contentEditable', editable);
}
function request(jsonString) {
$.ajax({
url: "/updatesetvil",
type: "POST",
data: jsonString,
dataType: "text",
success: function(){
alert(\"success\");
},
error:function(){
alert(\"failure\");
}
});
};
</script>
Servlet:
public class UpdateSetvil extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
List<SetvilJsonAttributes> setvilAttrs = new LinkedList<SetvilJsonAttributes>();
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Inside servlet");
// 1. get received JSON data from request
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String json = "";
if(br != null){
json = br.readLine();
}
System.out.println(json.toString()); // [{"id":"","notes":""},{"id":"18001","notes":"fdafd"},{"id":"8350","notes":"daggda"},{"id":"8056","notes":"gfdagdfa"}]
// 2. initiate jackson mapper
ObjectMapper mapper = new ObjectMapper();
// 3. Convert received JSON to Class
SetvilJsonAttributes setvilatt = mapper.readValue(json, SetvilJsonAttributes.class);
// 4. Set response type to JSON
response.setContentType("application/json");
setvilAttrs.add(setvilatt);
for (int i=0;i< setvilatt.size(); i++) {
System.out.println(setvilatt.get(i).getId());
}
}
private class SetvilJsonAttributes {
Integer id;
String notes;
String eta;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getEta() {
return eta;
}
public void setEta(String eta) {
this.eta = eta;
}
}
}
Error: java.io.IOException: Error parsing JSON request string
I kindly request anyone to help me on this.I have been stuck and unable to proceed further.
try this,
$.ajax({
url: "/updatesetvil",
type: "POST",
// The key needs to match your method's input parameter (case-sensitive).
data: { jsonString: jsonString},
contentType: "application/json; charset=utf-8"
dataType: "text",
success: function(data){
alert(\"success\"+data);
},
error:function(){
alert(\"failure\"+data);
}
});
Suggestion
If you are getting issues while parsing a JSON string then I can help you to parse the JSON string into Java object using GSON library as illustrated in below sample code.
Please note id should be String otherwise it will result into NumberFormatException for empty id values.
Sample code:
class SetvilJsonAttributes {
private String id;
private String notes;
// getter & setter
}
String jsonString="[{\"id\":\"\",\"notes\":\"\"},{\"id\":\"18001\",\"notes\":\"fdafd\"},{\"id\":\"8350\",\"notes\":\"daggda\"},{\"id\":\"8056\",\"notes\":\"gfdagdfa\"}]";
Type type = new TypeToken<ArrayList<SetvilJsonAttributes>>() {}.getType();
ArrayList<SetvilJsonAttributes> data = new Gson().fromJson(jsonString,type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
output:
[
{
"id": "",
"notes": ""
},
{
"id": "18001",
"notes": "fdafd"
},
{
"id": "8350",
"notes": "daggda"
},
{
"id": "8056",
"notes": "gfdagdfa"
}
]
If you don't want to change the type of id field then you can try with JsonDeserializer to deserializer it as per your need.
Please have a look at my another posts here and here for JsonDeserializer.
See these three lines:
System.out.println(json.toString()); // [{"id":"","notes":""},{"id":"18001","notes":"fdafd"},{"id":"8350","notes":"daggda"},{"id":"8056","notes":"gfdagdfa"}]
ObjectMapper mapper = new ObjectMapper();
SetvilJsonAttributes setvilatt = mapper.readValue(json, SetvilJsonAttributes.class);
The value of json is a JSON array. But, then you map it to SetvilJsonAttributes, which does not support JSON array. You can convert this json to a List of SetvilJsonAttributes using:
ObjectMapper mapper = new ObjectMapper();
ArrayList<SetvilJsonAttributes> setvilatt = mapper.readValue(json, new TypeReference<ArrayList<SetvilJsonAttributes>>(){});
I have used JSONArray and it worked out
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Inside servlet");
Connection connector = MysqlConnector.getDBCon();
StringBuffer sb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
json = sb.toString();
} catch (Exception e) {
System.out.println("Exception while reading JSON String");
e.printStackTrace();
}
System.out.println("String is " + json);
try {
JSONArray inputArray = new JSONArray(json);
for (int i=0; i < inputArray.length(); i++) {
JSONObject c = inputArray.getJSONObject(i);
String id = c.getString("id");
String notes = c.getString("notes");
System.out.println(id + "--> " + notes);
} catch (JSONException e) {
// crash and burn
System.out.println("Parse exeception for array");
e.printStackTrace();
}
}
Related
I have the following JSON file :
{
"btnsAssign": [
{
"btnCode": 1,
"btnItemTXT": "Baguette",
"btnItemCode": 1001,
"btnAvatarPath": "path"
},
{
"btnCode": 2,
"btnItemTXT": "Petit Pain",
"btnItemCode": 1002,
"btnAvatarPath": "path"
}
]
}
I have the below class :
BtnMenuAssignModel.java
public class BtnMenuAssignModel {
#SerializedName("btnsAssign")
#Expose
private List<BtnsAssign> btnsAssign = null;
public List<BtnsAssign> getBtnsAssign() {
return btnsAssign;
}
public void setBtnsAssign(List<BtnsAssign> btnsAssign) {
this.btnsAssign = btnsAssign;
}
}
BtnsAssign.java
public class BtnsAssign {
#SerializedName("btnCode")
#Expose
private Integer btnCode;
#SerializedName("btnItemTXT")
#Expose
private String btnItemTXT;
#SerializedName("btnItemCode")
#Expose
private Integer btnItemCode;
#SerializedName("btnAvatarPath")
#Expose
private String btnAvatarPath;
public Integer getBtnCode() {
return btnCode;
}
public void setBtnCode(Integer btnCode) {
this.btnCode = btnCode;
}
public String getBtnItemTXT() {
return btnItemTXT;
}
public void setBtnItemTXT(String btnItemTXT) {
this.btnItemTXT = btnItemTXT;
}
public Integer getBtnItemCode() {
return btnItemCode;
}
public void setBtnItemCode(Integer btnItemCode) {
this.btnItemCode = btnItemCode;
}
public String getBtnAvatarPath() {
return btnAvatarPath;
}
public void setBtnAvatarPath(String btnAvatarPath) {
this.btnAvatarPath = btnAvatarPath;
}
}
I need to update some object E.G: object btnItemTXT index 1 from "Petit Pain" to "Pain Complet", How can I?
First convert JSON file to BtnMenuAssignModel then modify BtnMenuAssignModel and convert BtnMenuAssignModel to JSON file:
Gson gson = new Gson();
// read initial json from jsonfile.json
FileReader reader = new FileReader(new File("D:\\codes\\gitlab\\jsonfile.json"));
BtnMenuAssignModel newModel = gson.fromJson(reader, BtnMenuAssignModel.class);
// modify the json object
newModel.getBtnsAssign().forEach(btnsAssign -> {
if (btnsAssign.getBtnCode() == 2) {
btnsAssign.setBtnItemTXT("Pain Complet");
}
});
// write new json string into jsonfile1.json file
File jsonFile = new File("D:\\codes\\gitlab\\jsonfile1.json");
OutputStream outputStream = new FileOutputStream(jsonFile);
outputStream.write(gson.toJson(newModel).getBytes());
outputStream.flush();
This is the right code working for me :
String file = "c:/Users/QAXX2121/Documents/a.json";
try {
Gson gson = new Gson();
// read initial json from jsonfile.json
FileReader reader = new FileReader(new File(file));
BtnMenuAssignModel newModel = gson.fromJson(reader, BtnMenuAssignModel.class);
// modify the json object
newModel.getBtnsAssign().forEach(btnsAssign -> {
if (btnsAssign.getBtnCode() == 2) {
btnsAssign.setBtnItemTXT("Taher");
}
});
// write new json string into jsonfile1.json file
File jsonFile = new File(file);
OutputStream outputStream = new FileOutputStream(jsonFile);
outputStream.write(gson.toJson(newModel).getBytes());
outputStream.flush();
{ "StatusCode": 200, "StatusDescription": "OK", "ErrorMessage":
"", "ErrorDetail": "", "Results": [
{
"Key": "AccessTokens",
"Value": "[{\"Key\":\"XXXXX",
\"Value\":\"BABABA\"},{\"Key\":\"DIDADIDA\",\"Value\":\"YYYYY"
} ]"}]}
This is the response i will get when i success call the API. The datatype of "Results" is List. Can anyone explain for me how to get the "Key" and the "Value".
My Object Classes
public class KeyValueItem {
private String Key;
private String Value;
public String getKey() {
return Key;
}
public void setKey(String key) {
Key = key;
}
public String getValue() {
return Value;
}
public void setValue(String value) {
Value = value;
}
}
Response Class
public class RestServiceResponse {
#SerializedName("StatusCode")
#Expose
public int StatusCode;
public int getStatusCode() {
return StatusCode;
}
#SerializedName("StatusDescription")
#Expose
public String StatusDescription;
public String getStatusDescription() {
return StatusDescription;
}
#SerializedName("ErrorMessage")
#Expose
public String ErrorMessage;
public String getErrorMessage() {
return ErrorMessage;
}
#SerializedName("ErrorDetail")
#Expose
public String ErrorDetail;
public String getErrorDetail() {
return ErrorDetail;
}
#SerializedName("Results")
#Expose
public List<KeyValueItem> Results;
public List<KeyValueItem> getResults() {
return Results;
}
}
Anyone help please =(
Some of my code:
public void onResponse(Call<RestServiceResponse> call, Response<RestServiceResponse> response) {
Log.i("ddsddsadsa", String.valueOf(response.code()));
RestServiceResponse restServiceResponse = response.body();
if(restServiceResponse.getStatusCode() == 200){
List<KeyValueItem> list = response.body().getResults();
JSONArray jsonArray = new JSONArray(list);
try {
JSONObject job = jsonArray.getJSONObject(1);
String testttt = job.getString("Key");
Log.i("dsadsadsadas", testttt);
} catch (JSONException e) {
e.printStackTrace();
}
}
2 things you have to understand first.
Your JSON data is not in valid format. It contains \ (slashes) to escape double quotes in key-value pair. To confirm whether the returned JSON data is valid or not please copy & paste your JSON response into JSON validator and Formatter. Maybe problem in server script.
If you're using GsonConvertorFactory with Retrofit, Retrofit will automatically converts JSON response data to POJO internally. So, you don't need parse it again inside onResponse() method. If you get proper JSON response from server side then use it like below.
public void onResponse(Call<RestServiceResponse> call, Response<RestServiceResponse> response) {
// code....
RestServiceResponse restServiceResponse = response.body();
if (restServiceResponse.getStatusCode() == 200) {
List<KeyValueItem> list = response.body().getResults();
for(int i = 0; i < list.size(); i++) {
KeyValueItem kvi = list.get(i);
// do whatever you want with kvi object
}
}
}
public void onResponse(Call<RestServiceResponse> call, Response<RestServiceResponse> response) {
Log.i("ddsddsadsa", String.valueOf(response.code()));
RestServiceResponse restServiceResponse = response.body();
if(restServiceResponse.getStatusCode() == 200){
List<KeyValueItem> list = response.body().getResults();
for(KeyValueItem keyValueItem : list) {
String key = keyValueItem.getKey();
String value = keyValueItem.getValue();
Log.i("Keykeykey", key);
}
try {
JSONArray jsonArray = new JSONArray(value);
for(int i = 0; i < jsonArray.length();i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String keykey = obj.getString("Key");
String VAlll = obj.getString("Value");
Log.i("c1111",keykey);
Log.i("c222222", VAlll);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}else if(restServiceResponse.getErrorMessage() != null){
builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle("Error");
builder.setMessage(restServiceResponse.getErrorMessage());
builder.setPositiveButton("Ok",null);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
OK. Btw. i have try this to get my result. and it works!
To answer those about a invalid JSON format maybe because i have changed the value of the JSON so may have some mistake on it.
Below is the final log i get:
74/com.appandus.user.konnect I/Keykeykey: AccessTokens 07-12
17:14:38.177 6274-6274/com.appandus.user.konnect I/c1111: XXXXX 07-12
17:14:38.177 6274-6274/com.appandus.user.konnect I/c222222: BABABA
07-12 17:14:38.177 6274-6274/com.appandus.user.konnect I/c1111: NS/NH
: DIDAIDA 07-12 17:14:38.177 6274-6274/com.appandus.user.konnect
I/c222222: YYYYYY
Please have a look at the below code snippet.
I had a look at some solutions provided on stackoverflow for adding String to a list.
They did not work out well in the below case.
#RequestMapping(value = "/rest/EmployeeDept/", method = RequestMethod.GET)
// ResponseEntity is meant to represent the entire HTTP response
public ResponseEntity<EmployeeDeptResponse> getDept()
{
EmployeeDeptResponse deptResponse = new EmployeeDeptResponse();
HttpStatus httpStatus;
List<EmployeeDept> employeeDeptList = new ArrayList<EmployeeDept>();
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(
"http://localhost:8082/rest/EmployeeDept/");
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
employeeDeptList.add(output);
}
deptResponse.setItems(employeeDeptList);
httpClient.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpStatus = HttpStatus.OK;
return new ResponseEntity<EmployeeDeptResponse>(deptResponse,httpStatus);
}
I am getting an error in the while loop as "add in list can not be applied to java.lang.String"
The list of type "EmployeeDept".The EmployeeDept class looks like this:-
package com.springboot.postrgres.model;
import java.io.Serializable;
public class EmployeeDept implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String dept;
public EmployeeDept() {
}
public EmployeeDept(int id, String dept) {
this.id = id;
this.dept = dept;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDept() {
return dept;
}
public void setDept(String name) {
this.dept = dept;
}
}
In the above code I have a list "employeeDeptList" and a string "Output".
I need to add this string to the list.
Can any of you provide suitable suggestions.
Thanks in advance.
employeeDeptList is of type ArrayList<EmployeeDept>.
List<EmployeeDept> employeeDeptList = new ArrayList<EmployeeDept>();
output on the other hand is of type String
String output;
So when you do employeeDeptList.add(output);, you are trying to add a String to your employeeDeptList, when it should be an EmployeeDept.
So you either make output an EmployeeDept or you rethink what you want to do with it.
As a suggestion, I am going to assume that your output should contain the information you need to create an EmployeeDept. You probably want to parse that information and create a EmployeeDept dept = new EmployeeDept(parsedId, parsedDept); and then add it to employeeDeptList as employeeDeptList.add(dept);
employeeDeptList is a list of EmployeeDept object. You are trying to add a String to the list of EmployeeDept. Which is not posssible unless you change the type of output variable to EmployeeDept.
If you response is a valid json (specified header), why won't you try to map it to objects?
ObjectMapper mapper = new ObjectMapper();
//assuming your response entity content is a list of objects (json array, since you specified header 'application/json'
String jsonArray = String theString = IOUtils.toString(response.getEntity().getContent(), encoding);
employeeDeptList = List<Employee> list = mapper.readValue(jsonString, TypeFactory.defaultInstance().constructCollectionType(List.class, employeeDeptList.class));
//assuming your response is a single object
String json = String theString = IOUtils.toString(response.getEntity().getContent(), encoding);
employeeDeptList.add(mapper.readValue(json, Employee.class));
//assuming every line of content is an object (does not really make sense)
BufferedReader br = new BufferedReader(ew InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
employeeDeptList.add(mapper.readValue(output, Employee.class));
}
There is a problem in your code.
while ((output = br.readLine()) != null) {
employeeDeptList.add(output);
}
output is a String and you are trying to add that to a List<EmployeeDept>. You can't do that. If you want to add output to a List, you should create a List of Strings. Something like List<String>
As you mentioned, what you are getting is,
{
"1499921014230": {
"id": 1499921014230,
"dept": "mechanics"
},
"1499921019747": {
"id": 1499921019747,
"dept": "civil"
}
}
If you can change that , you can try to change it to a simple array of objects,
[
{
"id": 1499921014230,
"dept": "mechanics"
},
{
"id": 1499921019747,
"dept": "civil"
}
]
Add below dependency if you use maven, or just add the .jar to the lib,
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
Then try something like this,
while ((output = br.readLine()) != null) {
JSONArray jsonArr = new JSONArray(output);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
String dept = jsonObj.getString("dept");
int id = jsonObj.getInt("id");
System.out.println("id : " + id + " dept : " + dept);
employeeDeptList.add(new EmployeeDept(id, dept));
}
}
I am trying to pass JSON string using javascript (dojo xhr) to a POST method implemented using Apache Wink library.
Below is my javascript code using dojo/_base/xhr:
var data = JSON.stringify({"id" : "1", "status" : "Red", "title" : "Incident 1"});
xhr.post
(
{
headers: {
'Content-Type': 'application/json'
},
handleAs : "json",
content : data,
load : function(data, ioArgs)
{
alert(data);
},
error : function(error, ioArgs)
{
alert(error);
}
}
);
Below is my POST method code in Java:-
#POST
#Path("saveIncidents")
#Consumes(MediaType.APPLICATION_JSON)
public void saveIncidents(String incidentData)
{
try {
JSONObject jsonObject = new JSONObject(incidentData);
} catch (JSONException e) {
e.printStackTrace();
}
}
However, I get exception as:
A JSONObject text must begin with '{' at character 1
Below is what I get in String variable 'incidentData':
0=%7B&1=%22&2=i&3=d&4=%22&5=%3A&6=%22&7=1&8=%22&9=%2C&10=%22&11=i&12=n&13=c&14=i&15=d&16=e&17=n&18=t&19=S&20=t&21=a&22=t&23=u&24=s&25=%22&26=%3A&27=%22&28=R&29=e&30=d&31=%22&32=%2C&33=%22&34=i&35=n&36=c&37=i&38=d&39=e&40=n&41=t&42=T&43=i&44=t&45=l&46=e&47=%22&48=%3A&49=%22&50=I&51=n&52=c&53=i&54=d&55=e&56=n&57=t&58=%20&59=1&60=%22&61=%7D
Does anyone know how to go about it? Thanks in advance for your help.
Are you sure of how stringify is used? Here is one example which I got from msdn.
var contact = new Object();
contact.firstname = "Jesper";
contact.surname = "Aaberg";
contact.phone = ["555-0100", "555-0120"];
var jsonText = JSON.stringify(contact);
document.write(jsonText);
For now I have resolved it like this -
#POST
#Path("saveIncidents")
#Consumes(MediaType.APPLICATION_JSON)
public void saveIncidents(String encodedIncidentData) {
JSONObject jsonObject = null;
String incidentData = "";
StringTokenizer mainTokenizer = new StringTokenizer(encodedIncidentData, "&");
while(mainTokenizer.hasMoreElements()) {
String token = mainTokenizer.nextElement().toString();
StringTokenizer innerTokenizer = new StringTokenizer(token, "=");
String character = null;
while(innerTokenizer.hasMoreElements()) {
character = innerTokenizer.nextElement().toString();
}
if(character.equals("%2C")){
character = ",";
}
else if(character.equals("%22")){
character = "\"";
}
else if(character.equals("%7B")){
character = "{";
}
else if(character.equals("%7D")){
character = "}";
}
else if(character.equals("%3A")){
character = ":";
}
else if(character.equals("%5D")){
character = "]";
}
else if(character.equals("%5B")){
character = "[";
}
else if(character.equals("%20")){
character = " ";
}
incidentData += character;
}
try {
jsonObject = new JSONObject(incidentData);
} catch (JSONException e) {
e.printStackTrace();
}
}
Still, please let me know if any efficient solution is there. Thanks.
I am trying to write an automated Java test where the code will go to a specified URL, read the JSON data and print it up.
Here is the JSON I am trying to access;
{
"status": "success",
"records": [
{
"timestamp": 1381222871868,
"deviceId": "288",
"temperature": 17
},
{
"timestamp": 1381222901868,
"deviceId": "288",
"temperature": 17
},
{
"timestamp": 1381222931868,
"deviceId": "288",
"temperature": 17
},
]}
As you can see I only have 3 elements, Timestamp, DeviceId and Temperature.
What I am ultimately aiming for it to be able to get 2 Timestamp values and take one value away from the other, if that is possible.
Anyway I have been trying to do this all day and am having no luck whatsoever. I was recommended to use Gson and I have included the jar files into my classpath.
If anyone knows anything or can help me in any way it would be much appreciated as I have exhausted Google and myself trying to work this out.
Here is the code I have to display the full list, but I do not fully understand it and so far can't manipulate it to my advantage;
public static void main(String[] args) throws Exception
{
String jsonString = callURL("http://localhost:8000/eem/api/v1/metrics/temperature/288");
System.out.println("\n\njsonString: " + jsonString);
// Replace this try catch block for all below subsequent examples
/*try
{
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println("\n\njsonArray: " + jsonArray);
}
catch (JSONException e)
{
e.printStackTrace();
}*/
try
{
JSONArray jsonArray = new JSONArray(jsonString);
int count = jsonArray.length(); // get totalCount of all jsonObjects
for(int i=0 ; i< count; i++)
{ // iterate through jsonArray
JSONObject jsonObject = jsonArray.getJSONObject(i); // get jsonObject # i position
System.out.println("jsonObject " + i + ": " + jsonObject);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
public static String callURL(String myURL)
{
//System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try
{
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
{
urlConn.setReadTimeout(60 * 1000);
}
if (urlConn != null && urlConn.getInputStream() != null)
{
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null)
{
int cp;
while ((cp = bufferedReader.read()) != -1)
{
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
}
catch (Exception e)
{
throw new RuntimeException("Exception while calling URL:"+ myURL, e);
}
return sb.toString();
}
Cheers
I had read the values from file but you can read from URL, the extracting process code is present inside extractJson() method.
public static void main(String [] args)
{
try
{
FileInputStream fis=new FileInputStream("testjson.json");
int b=0;
String val="";
while((b=fis.read())!=-1)
{
val=val+(char)b;
}
extractJson(val);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void extractJson(String json)
{
try
{
JSONObject jobject=new JSONObject(json);
System.out.println("Json object Length: "+jobject.length());
System.out.println("Status: "+jobject.getString("status"));
JSONArray jarray=new JSONArray(jobject.getString("records"));
System.out.println("Json array Length: "+jarray.length());
for(int j=0;j<jarray.length();j++)
{
JSONObject tempObject=jarray.getJSONObject(j);
System.out.println("Timestamp: "+tempObject.getString("timestamp"));
System.out.println("Device Id: "+tempObject.getString("deviceId"));
System.out.println("Temperature: "+tempObject.getString("temperature"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
You could use ArrayList to store the values which will be available inside for loop. From your question you need to pass jsonString this variable to the extractJson() method. Use org.json jar file to process json. If you could alter this for gson then it'll be good for your requirement.
here's how to do it via Google-Gson
class MyRecord
{
private long timestamp;
private String deviceId;
private Integer temperature;
//Getters & setters
}
public static void main(String... args){
String myJsonString=callUrl("http://mydomain.com/x.json");
JsonParser jp = new JsonParser();
JsonElement ele = jp.parse(myJsonString);
Gson gg = new Gson();
Type type = new TypeToken<List<MyRecord>>() {
}.getType();
List<MyRecord> lst= gg.fromJson(ele.getAsJsonObject().get("records"), type);
//Now the json is parsed in a List of MyRecord, do whatever you want to with it
}
An "high-level" Gson parsing answer:
package stackoverflow.questions.q19252374;
import java.util.List;
import com.google.gson.Gson;
public class Q19252374 {
class Record {
Long timestamp;
String deviceId;
Long temperature;
}
class Container {
List<Record> records;
}
public static void main(String[] args) {
String json = "{ \"status\": \"success\", \"records\": [{\"timestamp\": 1381222871868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222901868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222931868,\"deviceId\": \"288\",\"temperature\": 17 } ]} ";
Gson g = new Gson();
Container c = g.fromJson(json, Container.class);
for (Record r : c.records)
System.out.println(r.timestamp);
}
}
Of course this is the result:
1381222871868
1381222901868
1381222931868