I want to loop through the questionnaires by using the for loop to set the value of the EMAIL_TO_CLIENT_IND.
The value inside the "path" is QUESTIONNAIRES/SUB_QUESTION/EMAIL_TO_CLIENT_IND.
The first "if" is if the level path in JSON is just one Ex. "Questionnaires". And the "else" is for the path more than 1 Ex. "Questionnaires/Question".
My current idea is put the jObject.getJSONObject() inside the "else" for loop.
You can use the JSONArray as follows
String json="{\"QUESTIONNAIRES\":[{\n" +
" \"SUB_QUESTION\":[{\n" +
" \"EMAIL_TO_CLIENT_IND\":\"N\"\n" +
" }]\n" +
"}]}";
try {
JSONObject mainObject=new JSONObject(json);
JSONArray questionnairesArray=mainObject.getJSONArray("QUESTIONNAIRES");
for (int i=0;i<questionnairesArray.length();i++){
JSONObject questionnairesObject= (JSONObject) questionnairesArray.get(i);
JSONArray subQuestionArray=questionnairesObject.getJSONArray("SUB_QUESTION");
for (int j=0;j<subQuestionArray.length();j++){
JSONObject subQuestionObject= (JSONObject) subQuestionArray.get(i);
subQuestionObject.put("EMAIL_TO_CLIENT_IND","Y");
}
}
Log.e("Output",mainObject.toString());
} catch (JSONException e) {
Log.e("Exception",e.getMessage());
}
Edited
can be solved using GSON library also
//frame data classes
class Response {
#SerializedName("QUESTIONNAIRES")
private List<Questionaire> questionaireList;
public List<Questionaire> getQuestionaireList() {
return questionaireList;
}
public void setQuestionaireList(List<Questionaire> questionaireList) {
this.questionaireList = questionaireList;
}
}
class Questionaire {
#SerializedName("SUB_QUESTION")
private List<SubQuestion> subQuestionList;
public List<SubQuestion> getSubQuestionList() {
return subQuestionList;
}
public void setSubQuestionList(List<SubQuestion> subQuestionList) {
this.subQuestionList = subQuestionList;
}
}
class SubQuestion {
#SerializedName("EMAIL_TO_CLIENT_IND")
private String emailToClientId;
public String getEmailToClientId() {
return emailToClientId;
}
public void setEmailToClientId(String emailToClientId) {
this.emailToClientId = emailToClientId;
}
}
//loop through data using GSON
Gson gson = new Gson();
String json = "{\"QUESTIONNAIRES\":[{\n" +
" \"SUB_QUESTION\":[{\n" +
" \"EMAIL_TO_CLIENT_IND\":\"N\"\n" +
" }]\n" +
"}]}";
Response response = gson.fromJson(json, Response.class);
for (Questionaire questionnaire : response.getQuestionaireList()) {
for (SubQuestion subQuestion : questionnaire.getSubQuestionList()) {
subQuestion.setEmailToClientId("Y");
}
}
Log.e("Output", gson.toJson(response));
Related
I have a json file consisting of a single array. the array consists of objects with the keys name, title, pay, age. How can I delete an entire object by the value of the Name key? I am using the "simple json" library, it is quite old, but it suits my purposes. Sorry, there is a lot of code, I don't know what to show. Thank.
public class Json {
static JSONArray jsonArray;
public static void JsonWriter(String filePath, String fullname, String age, String pay, String post) {
try {
JSONObject worker = new JSONObject();
worker.put("name", fullname);
worker.put("age", new Integer(age));
worker.put("post", post);
worker.put("pay", new Integer(pay));
jsonArray.add(worker);
FileWriter file = new FileWriter(filePath);
file.write(jsonArray.toString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//add object
public static void AddWorker() throws IOException, ParseException {
System.out.println("input name");
String name = handleInput();
System.out.println("input post");
String post = handleInput();
System.out.println("input age");
String age = handleInput();
System.out.println("input pay");
String pay = handleInput();
System.out.println("succes");
JsonWriter("res\\Worker List.json", name, age, pay, post);
WorkerList();
}
public static void DeleteWorker()
{
System.out.println(ansi().fg(RED).a("Input name").reset());
String name = handleInput();
}
//add object
public static void WorkerList() throws IOException, ParseException {
Iterator i = jsonArray.iterator();
while (i.hasNext())
{
System.out.println(Menu.Separator);
JSONObject innearObj = (JSONObject) i.next();
System.out.println("name: " + innearObj.get("name") + lineSeparator() +
"age: " + innearObj.get("age") + lineSeparator() +
"post: " + innearObj.get("post") + lineSeparator() +
"pay: " + innearObj.get("pay"));
}
System.out.println(Menu.Separator);
System.out.println("Add new object?" + lineSeparator() + "0 - Yes" + lineSeparator() + "1 - No");
switch(handleInput())
{
case ("0"):
AddWorker();
break;
}
}
//Parsing json file
public static void WorkersParser(String filePath)
{
try {
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(new FileReader(filePath));
jsonArray = (JSONArray) obj;
WorkerList();
} catch (IOException | ParseException e)
{
e.printStackTrace();
}
}
}
public static String handleInput() {
try {
String input;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
input = reader.readLine();
return input;
}
catch (Exception ignored) { }
return "";
}
////
[
{
"post":"post1",
"name":"name1",
"pay":1,
"age":1
},
{
"post":"post2",
"name":"name2", //if name = "post2", delete // {
"pay":2, // "post":"post2",
"age":2 // "name":"name2",
} // "pay":"2",
] // "age":2
// }
You can loop all of them, check for that parameter and remove() by the index:
String jsonString = "[{\"post\":\"post1\",\"name\":\"name1\",\"pay\":1,\"age\":1},{\"post\":\"post2\",\"name\":\"name2\",\"pay\":2,\"age\":2}]";
JSONArray arr = new JSONArray(jsonString);
String wordToDeleteBy = "name1";
System.out.println(arr.length()); //prints 2
for (int i = 0; i<arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
if (obj.has("name") && obj.get("name").equals(wordToDeleteBy)) {
arr.remove(i);
}
}
System.out.println(arr.length()); //prints 1
Take for example the class JSONObject.
And say I have the following method.
public JSONObject getObjectOrThrow(String name) {
JSONObject jsonObject = null;
try {
jsonObject = JSON.getJSONObject(name);
} catch (Exception e) {
System.out.println("JSON_ERROR : " + name);
e.printStackTrace();
}
return jsonObject;
}
How do I extend the JSONObject so that I'll end up with a method like.
JSONObject man = new JSONObject("name");
man.getObjectOrThrow("name");
Where "name" is the key to the child node of "man".
Also for reference, what is this called?
Custom Class
public class CustomJSONObjectProvider extends JSONObject {
public JSONObject getObjectOrThrow(String name) {
JSONObject jsonObject = null;
try {
jsonObject = JSON.getJSONObject(name);
} catch (Exception e) {
System.out.println("JSON_ERROR : " + name);
e.printStackTrace();
}
return jsonObject;
}
// all the other custom methods that you want to override
}
And the way you use it
CustomJSONObjectProvider customJSONObjectProvider = new CustomJSONObjectProvider();
JSONObject jsonObject = customJSONObjectProvider.getObjectOrThrow("name");
It can also be static
public class CustomJSONObjectProvider extends JSONObject {
public static JSONObject getObjectOrThrow(String name) {
JSONObject jsonObject = null;
try {
jsonObject = JSON.getJSONObject(name);
} catch (Exception e) {
System.out.println("JSON_ERROR : " + name);
e.printStackTrace();
}
return jsonObject;
}
// all the other custom methods that you want to override
}
Its usage
JSONObject jsonObject = CustomJSONObjectProvider.getObjectOrThrow("name");
This is my JSonArray
{
"vendor":[
{
"vendor_name":"Tapan Moharana",
"vendor_description":"",
"vendor_slug":"tapan",
"vendor_logo":null,
"contact_number":null
}
],
"products":[
{
"name":"Massage",
"price":"5000.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/2\/9\/29660571-beauty-spa-woman-portrait-beautiful-girl-touching-her-face.jpg"
},
{
"name":"Chicken Chilly",
"price":"234.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/c\/h\/cheicken.jpg"
},
{
"name":"Chicken Biryani",
"price":"500.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/placeholder\/default\/image_1.jpg"
}
]
}
and this is my java code:
JSONObject jsono = new JSONObject(response);
JSONArray children = jsono.getJSONArray("vendor");
JSONArray childrenProducts = jsono.getJSONArray("products");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
System.out.print(jsonData.getString("products") + "<----");
}
for(int i=0;i<childrenProducts.length();i++){
JSONObject jsonData = childrenProducts.getJSONObject(i);
System.out.println("inside products");
System.out.print(jsonData.getString("name") + "<----dd");
}
The first for loop is working fine but the second forloop is not.. i dont get anything if i try to execute those print statements inside the second for loop.. please help me!!
Why don't you use Gson to get parse the JSON string simply?
You need to declares classes first to match the JSON response like this.
public class Vendor {
private String vendor_name;
private String vendor_description;
private String vendor_slug;
private String vendor_logo;
private String contact_number;
public Vendor() {
}
public String getVendor_name() {
return vendor_name;
}
public String getVendor_description() {
return vendor_description;
}
public String getVendor_slug() {
return vendor_slug;
}
public String getVendor_logo() {
return vendor_logo;
}
public String getContact_number() {
return contact_number;
}
}
...
public class Product {
private String name;
private String price;
private String image;
public Product() {
}
public String getName() {
return name;
}
public String getPrice() {
return price;
}
public String getImage() {
return image;
}
}
Now declare the Response class like this
public class Response {
private List<Vendor> vendor;
private List<Product> products;
public Response() {
}
public List<Vendor> getVendor() {
return vendor;
}
public List<Product> getProducts() {
return products;
}
}
Now, once you've the JSON string its easy to bounce the data using GSON into the Response class like this.
Gson gson = new Gson();
Response mResponse = gson.fromJson(jsonString, Response.class);
Simple!
It is not going in your second for loop because there is SomeException in your first for loop.
Your execution will be thrown out to any catch() clause, and the further execution will not be done including your second for loop.
Just try putting that up like this:
JSONObject jsono = new JSONObject(response);
JSONArray children = jsono.getJSONArray("vendor");
JSONArray childrenProducts = jsono.getJSONArray("products");
//this will be executed now..!!
for(int i=0;i<childrenProducts.length();i++){
JSONObject jsonData = childrenProducts.getJSONObject(i);
System.out.println("inside products");
System.out.print(jsonData.getString("name") + "<----dd");
}
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
System.out.print(jsonData.getString("products") + "<----");
}
This is how i solved it:
try {
JSONObject jsono = new JSONObject(response);
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
System.out.print(jsonData.getString("products") + "<----");
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject jsono = new JSONObject(response);
JSONArray childrenProducts = jsono.getJSONArray("products");
System.out.println(childrenProducts.length()+"LENGTH");
for(int i=0; i<childrenProducts.length(); i++){
JSONObject jsonData1 = childrenProducts.getJSONObject(i);
System.out.println(childrenProducts.length() + "LENGTH");
System.out.print(jsonData1.getString("name") + "<----dd");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
just had to take two separate try blocks... can someone please tell why was it not working in one try block? the above code works
Ok so I got here is my sample JSON:
{
"messages":[
{
"receiver":"60:51:2c:93:6e:02",
"sender":"60:51:2c:93:6e:01",
"location":[
{
"longitude":"26.89478",
"latitude":"122.779953"
}
]
}
]
,"isSuccess":"true"
}
How can I retrieve every data inside it?
This is only what I got:
JSONObject jsonObject = parser.makeHttpRequest(someurl);
JSONArray messages = jsonObject.getJSONArray("messages");
If you are using the org.json lib
String json = "{\"messages\":[{\"receiver\":\"60:51:2c:93:6e:02\",\"sender\":\"60:51:2c:93:6e:01\",\"location\":[{\"longitude\":\"26.89478\",\"latitude\":\"122.779953\"}]}],\"isSuccess\":\"true\"}";
try {
JSONObject jsonObject = new JSONObject(json);
Boolean isSuccess = jsonObject.getBoolean("isSuccess");
JSONArray messages = jsonObject.getJSONArray("messages");
JSONObject firstElement = messages.getJSONObject(0);
String sender = firstElement.getString("sender");
JSONArray locationArray = firstElement.getJSONArray("location");
JSONObject firstLocation = locationArray.getJSONObject(0);
Double lng = firstLocation.getDouble("longitude");
Double lat = firstLocation.getDouble("latitude");
Log.d("Result", "isSuccess: " + String.valueOf(isSuccess)
+"\n Sender: " + String.valueOf(sender)
+"\n Latitude: " + String.valueOf(lat)
+"\n Longitude: " + String.valueOf(lng));
} catch (JSONException e) {
e.printStackTrace();
}
Or with less lines of code
Boolean isSuccess = jsonObject.getBoolean("isSuccess");
String sender = jsonObject.getJSONArray("messages").getJSONObject(0).getString("sender");
JSONObject firstLocation = jsonObject.getJSONArray("messages").getJSONObject(0).getJSONArray("location").getJSONObject(0);
Double lng = firstLocation.getDouble("longitude");
Double lat = firstLocation.getDouble("latitude");
What I also like with this library are the opt..() methods like optDouble() or optJSONObject() to avoid nested try/catch and define a default value if the key you are looking for doesn't exist.
I would suggest use JSCKSON APIs
refer below code
public static void main(String[] args) {
System.out.println("Hi");
String json = "{\"messages\":[{\"receiver\":\"60:51:2c:93:6e:02\",\"sender\":\"60:51:2c:93:6e:01\",\"location\":[{\"longitude\":\"26.89478\",\"latitude\":\"122.779953\"}]}],\"isSuccess\":\"true\"}";
ObjectMapper om = new ObjectMapper();
try {
JsonNode node = om.readTree(json);
System.out.println(node.get("messages").get(0).get("receiver"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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