I have this json:
{
"sid": "BiQo7DA4lMoRkeGN8mdfBXackyBarCSSauQtNRRKOmcfo2Ah0XCjaI1yevEoxWa09TkTOYrwGixRMvBr15h1d2",
"submissions": [{
"submission_id": "1104764"
}, {
"submission_id": "1104765"
}]
}
How can I in AndroidStudio get a list of items by submission_id?(there is always 30 items in "submissions")
Thanks
UPDATED
I'm trying with this code but show exception.
for (int i = 0; i < jObject.length(); i++) {
JSONObject subm = jObject.getJSONObject("submissions");
JSONObject jObj = subm.getJSONObject(String.valueOf(i));
testdata = testdata + " " + jObject.getString("submission_id");
//
}
I basically want to get all the elements inside the "submissions"...
Path : POJO classes -> GSON -> list
You can use Google GSON to read JSON into Java objects.
POJO
public class Submission
{
public String submission_id;
public Submission(String submission_id)
{
this.submission_id = submission_id;
}
}
public class SubmissionObject
{
public String sid;
public List<Submission> submissions;
public SubmissionObject(String sid,List<Submission> submissions)
{
this.sid = sid;
this.submissions = submissions;
}
}
POJOs are ready. Let's parse the JSON response by using GSON.
public List<Submission> submissions = new ArrayList<>();//your list holds the all submissions.
Gson gson = new Gson();// initialize GSON parser
SubmissionObject object = gson.fromJson(jsonResponse.toString(), SubmissionObject.class); //get the object
submissions = object.submissions; // set list
Try this one:
if (!jObject.isNull("submissions")) {
JSONArray submissions = jObject.getJSONArray("submissions");
for(int i = 0; i < submissions.length(); i++) {
JSONObject submission = submissions.getJSONObject(i);
String submissionId = submission.getString("submission_id");
}
}
Related
I want to add the elements to JSON array from the Java GUI at runtime
but every time the new array is created in JSON file
Java GUI to enter data:
String _itemType = txtItemType.getText();
int _itemQuantity = Integer.parseInt(txtItemQuantity.getText());
JSONWriteExample obj = new JSONWriteExample(_itemType, _itemQuantity);
obj.jsonParse();
JSON:
public JSONWriteExample(String type, int number) {
this.type = type;
this.quantity = number;
}
public void jsonParse() throws IOException {
JSONObject jo = new JSONObject();
Map m = new LinkedHashMap(4);
JSONArray ja = new JSONArray();
m = new LinkedHashMap(2);
m.put("Item Type", type);
m.put("Quantity", quantity);
ja.add(m);
jo.put("Items", ja);
FileWriter file=new FileWriter("jsonArray.json",true);
file.append(jo.toString());
file.flush();
file.close();
}
I expect the output like:
{
"Items":[
{
"Item Type":"TV",
"Quantity":3
},
{
"Item Type":"phone",
"Quantity":3
}
]
}
But new array is created each time like:
{
"Items":[
{
"Item Type":"TV",
"Quantity":3
}
]
}{
"Items":[
{
"Item Type":"phone",
"Quantity":3
}
]
}
As #fabian mentioned in the comment - you should first parse the file content, modify and overwrite the file. Here is a sample code how to achieve that:
First of all, I don't know what json library you're using, but I would strongly suggest to use the following:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
It will generally ease your work with json. If you don't want to use libraries you can still follow the instruction, but adapt it for your needs. The whole implementation is like this:
public class JSONWriteExample {
private static final String FILE_NAME = "jsonArray.json";
private static final Path FILE_PATH = Paths.get(FILE_NAME);
private final String type;
private final int quantity;
public JSONWriteExample(String type, int quantity) {
this.type = type;
this.quantity = quantity;
}
public void jsonParse() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
if (Files.notExists(FILE_PATH)) {
Files.createFile(FILE_PATH);
objectMapper.writeValue(FILE_PATH.toFile(), createItems(new ArrayList<>()));
}
Items items = objectMapper.readValue(FILE_PATH.toFile(), Items.class);
final List<Item> itemsList = items.getItems();
objectMapper.writeValue(FILE_PATH.toFile(), createItems(itemsList));
}
private Items createItems(List<Item> itemsList) {
final Item item = new Item();
item.setType(type);
item.setQuantity(quantity);
itemsList.add(item);
final Items items = new Items();
items.setItems(itemsList);
return items;
}
public static class Items {
private List<Item> items;
// Setters, Getters
}
public static class Item {
private String type;
private int quantity;
// Setters, Getters
}
}
Okay, what's going on in this code?
First of all, note the usage of Java 7 NIO - recommended way to work with files in java.
In jsonParse method we first check if file exists.
If it does - then we read it to the data class (Items) that describes our model. The reading part is done under the hood of this library, just the fileds of your json file should have the same names as the fields of the data classes (or specified with JsonAlias annotation.
If it doesn't - then we create it first and populate with the initial values.
ObjectMapper is the class from the library and it's used to read\write json files.
Now if we run this piece of code, e.g.
public static void main(String[] args) throws IOException {
JSONWriteExample example = new JSONWriteExample("TV", 3);
example.jsonParse();
JSONWriteExample example2 = new JSONWriteExample("phone", 3);
example2.jsonParse();
}
json file will look like:
{
"items": [
{
"type": "TV",
"quantity": 3
},
{
"type": "TV",
"quantity": 3
},
{
"type": "phone",
"quantity": 3
}
]
}
ArrayList<StylistArray>stylistsArr=new ArrayList<StylistArray>();
stylistsArr.add(new StylistArray("BqYWKWzs4r8SyGQvyqH2","18:30"));
stylistsArr.add(new StylistArray("at5kjx5FqIxbnMys8w4q","18:30"));
stylistsArr.add(new StylistArray("nFI5hxfIePx240dmqR0R","18:00"));
stylistsArr.add(new StylistArray("spxSj8UZem5uD0wL46EP","18:20"));
.
https://us-central.jshshskajshdala.net?dasa="+"2018-09-04"+"&ewsss="+"17:50"+"&stylist="+String.valueOf(stylistsArr)
I want to pass this arrayList along with the url. When I try to pass the array values the name of the model class is passing instead of values in the class
Example
I want to pass values like this:
[
{
"stylist": "BqYWKWzs4r8SyGQvyqH2",
"endTime": "18:30"
},
{
"stylist": "at5kjx5FqIxbnMys8w4q",
"endTime": "18:30"
},
{
"stylist": "nFI5hxfIePx240dmqR0R",
"endTime": "18:00"
},
{
"stylist": "spxSj8UZem5uD0wL46EP",
"endTime": "18:00"
}
]
Like #Mathan and #Cris say, you can simply using for looping to create your JSON string. For the following simple pojo:
public class StylistArray {
// use a final so the value can't be change once the object is created.
private final String stylist;
private final String endTime;
public StylistArray(String stylist, String endTime) {
this.stylist = stylist;
this.endTime = endTime;
}
public String getStylist() {
return stylist;
}
public String getEndTime() {
return endTime;
}
}
You can simply doing the following:
List<StylistArray> list = new ArrayList<>();
// assume you have add all items to the list.
JSONArray jsonArray = new JSONArray();
try {
// You need to use simple for loop instead the following foreach
// because foreach is slower than traditional loop.
for (StylistArray stylistArray : list) {
// create JSON object for each item
JSONObject jsonObject = new JSONObject();
jsonObject.put("stylist", stylistArray.getStylist());
jsonObject.put("endTime", stylistArray.getEndTime());
// append it to your JSON array.
jsonArray.put(jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
// Error happens, try to handle it.
}
Then you can get the string from the JSONArray. I'll let you to find out ;)
Add the Gson dependency in gradle
implementation 'com.google.code.gson:gson:2.8.4'
and rebuild your project
String json= new Gson().toJson(stylistsArr);
Now your "json" variable will have a json array.
Here is the code
List<Map<String, String>> values = new ArrayList<Map<String, String>>();
Map<String, String> maps = new HashMap<>();
maps.put("stylist", "BqYWKWzs4r8SyGQvyqH2");
maps.put("endTime", "18:30");
values.add(maps);
maps.put("stylist", "at5kjx5FqIxbnMys8w4q");
maps.put("endTime", "18:30");
values.add(maps);
maps.put("stylist", "nFI5hxfIePx240dmqR0R");
maps.put("endTime", "18:00");
values.add(maps);
JSONArray mJSONArray = new JSONArray(values);
I have written a program that does some probability calculations and gives its results in the form of arrays. I want to convert these results to JSON format, but I am having issues.
I want my json object to look like this:
{
"totalSuggestions": 6,
"routes": {
"rank_2": {
"Source": "ABC",
"Weight": "0.719010390625",
"Destination": "XYZ"
},
"rank_1": {
"Source": "XYZ",
"Weight": "0.7411458281249999",
"Destination": "ABC"
},
"rank_0": {
"Source": "LMN",
"Weight": "0.994583325",
"Destination": "PQR"
}
}
}
What I understood is that I need to have an object class with the structure of my objects. For now I am experimenting with the rank object only but failing to form the required JSON.
My code for the object structure:
public class Object {
int rank_;
public class Inner{
String Source;
String Destination;
String Weightage;
}
}
I can pass either an instance of Object or an instance of Inner to toJson() method so I either get {"rank_":1} or {"Source":"ABC","Destination":"XYZ","Weightage":"123"}.
I cant seem to put each of the inner object to the corresponding rank object.
I did it with relative ease with org.json but that library has some issues with Android studio so I had to switch to Gson. What I did earlier (which worked as well) was:
public JSONObject convertToJson(int mkr, String[][] result){
JSONObject outerObj = new JSONObject();
JSONObject innerObj = new JSONObject();
JSONObject[] temp = new JSONObject[mkr];
outerObj.put("totalSuggestions", marker);
outerObj.put("routes",innerObj);
for (int i=0;i<marker;i++){
String[] useless = result[i][0].split("-");
temp[i]= new JSONObject();
temp[i].put("Source",useless[0] );
temp[i].put("Destination", useless[1]);
temp[i].put("Weight", result[i][1]);
innerObj.put("rank_"+i, temp[i]);
}
System.out.println(outerObj.toString());
return outerObj;
}
Well, first: related objects should probably be in a class together. So lets start with a simple class:
public class Results {
int mkr;
String[][] result;
}
Now we want to serialize it. We could construct a different data structure, or we could just write our own custom serializer. We want to have our custom class to allow us to use Gson's type inference for doing so, plus the code is just easier to understand. I will show you how to serialize the data structure, and I'll leave the deserialization as an exercise for you.
We create a TypeAdapter<Results>:
public class ResultsAdapter extends TypeAdapter<Results> {
public Results read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
// exercise for you
return results;
}
public void write(JsonWriter writer, Results value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
writer.beginObject();
writer.name("totalSuggestions").value(value.mkr);
writer.name("routes");
writer.beginObject();
for(int i = 0; i < value.mkr; i++) {
writer.name("rank_"+i);
writer.beginObject();
String[] sourceDestSplit = result[i][0].split("-");
writer.name("Source").value(sourceDestSplit[0]);
writer.name("Destination").value(sourceDestSplit[1]);
writer.name("Weight").value(result[i][1]);
writer.endObject();
}
writer.endObject();
writer.endObject();
}
}
You can then call this method by doing (note: should only create the Gson object once, but I did it this way to keep the code short):
public String convertToJson(Results results) {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(new ResultsAdapter()):
Gson gson = builder.build();
return gson.toJson(results);
}
This will work you the way you've asked, but I strongly recommend using JSON's array syntax instead (using []). Try this instead:
public void write(JsonWriter writer, Results value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
writer.beginObject();
writer.name("totalSuggestions").value(value.mkr);
writer.name("routes");
writer.beginArray();
for(int i = 0; i < value.mkr; i++) {
writer.beginObject();
String[] sourceDestSplit = result[i][0].split("-");
writer.name("Source").value(sourceDestSplit[0]);
writer.name("Destination").value(sourceDestSplit[1]);
writer.name("Weight").value(result[i][1]);
writer.endObject();
}
writer.endArray();
writer.endObject();
}
Doing it this will will result in JSON that looks like this, which will be easier to deserialize on the other side and iterate through, because you won't have to dynamically generate maps for the keys.:
{
"totalSuggestions": 6,
"routes": [
{
"Source": "ABC",
"Weight": "0.719010390625",
"Destination": "XYZ"
},
{
"Source": "XYZ",
"Weight": "0.7411458281249999",
"Destination": "ABC"
},
{
"Source": "LMN",
"Weight": "0.994583325",
"Destination": "PQR"
}
]
}
I landed here while searching for a similar solution for the com.google.gson.JsonObject library. Now, I've found it:
JsonObject mainJson = new JsonObject();
JsonObject innerJson = new JsonObject();
innerJson.addProperty("#iot.id", "31");
mainJson.add("Datastream", innerJson); // <-- here the nesting happens
mainJson.addProperty("result", 12.3);
// fetch inner variable like this
System.out.println(mainJson.get("Datastream").getAsJsonObject().get("#iot.id").getAsString());
This works fine for me using the com.google.gson.JsonObject library.
For the record, this is what i did.
import java.util.*;
public class DataObject {
public int Suggestions;
HashMap<String, route> routes = new HashMap<>();
//constructor
public DataObject(int mkr, String[][] routesArr){
Suggestions = mkr;
{
for (int i=0;i<Suggestions;i++){
routes.put("rank_"+(i+1),new route(routesArr[i]));
}
}
}
//class to populate the hashmap
public class route{
public String Origin;
public String Destination;
public String Weight;
public route(String arr[]){
String[] splitter = arr[0].split("-");
this.Origin = splitter[0];
this.Destination = splitter[1];
this.Weight = arr[1];
}
}
}
I would like to know how to parse the following JSON using jackson library in java to construct the URI like http://api.statdns.com/google.com/cname
{
"status": {
"status": 200,
"msg": "SUCCESS"
},
"apicalls": [
{
"API": {
"method": "get",
"success": "200",
"baseURL": "http://api.statdns.com/",
"param1": "google.com/",
"param2": "cname",
"continue_on_fail": "1",
"add_header2": "'Accept', 'application/json'",
"add_header1": "'Content-Type', 'application/json'",
"client_id": "101"
},
"id": 1385
}
]
}
I have written bad code to parse the above json array. Following is the code i used,
public void parseJSON(String json) {
try{
JsonFactory factory = new JsonFactory();
JsonParser parser;
parser = factory.createJsonParser(json);
parser.setCodec(new ObjectMapper()); // to avoid IllegalStateException
JsonToken current;
current = parser.nextToken();
if (current != JsonToken.START_OBJECT) {
System.out.println("Error: root should be object: quiting.");
return;
}
while (parser.nextToken() != JsonToken.END_OBJECT) {
String fieldName = parser.getCurrentName();
// Move from field name to field value
current = parser.nextToken();
if (fieldName.equals("APIcalls")) {
JsonNode node = parser.readValueAsTree();
JsonNode currentJson = node.findValue("API");
System.out.println("Current JSON :: " + currentJson);
JsonNode url = currentJson.get("baseURL");
JsonNode param1 = currentJson.get("param1");
JsonNode param2 = currentJson.get("param2");
String baseURL = url.asText();
String params1 = param1.asText();
String params2 = param2.asText();
String uri = baseURL + params1 + params2;
System.out.println("URL :: " + uri);
initiateRESTCall(uri);
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Could anyone help me to know parsing the JSON using jackson? Help is highly appreciated.
If you are using jackson library, then you should go something like this:
I am using response from http://api.statdns.com/google.com/cname
public void parseJSON(String json) {
JSONObject parse = new JSONObject(data);
if(parse.get("question") instanceof JSONObject){
JSONObject questionJson = (JSONObject) parse.get("question");
System.out.println("Name"+questionJson.getString("name"));
System.out.println("Type"+questionJson.getString("type"));
System.out.println("Class"+questionJson.getString("class"));
}
else if(parse.get("question") instanceof JSONArray){
JSONArray questionJson = (JSONArray) parse.get("question");
String[] nameAttrib=new String[questionJson.length()];
String[] typeAttrib=new String[questionJson.length()];
String[] classAttrib=new String[questionJson.length()];
for(int i=0;i<questionJson.length();i++){
JSONObject questionJsonData=(JSONObject)questionJson.get(i);
nameAttrib[i]=questionJsonData.getString("name");
typeAttrib[i]=questionJsonData.getString("type");
classAttrib[i]=questionJsonData.getString("class");
System.out.println("Name: "+nameAttrib[i]);
System.out.println("Type: "+typeAttrib[i]);
System.out.println("Class: "+classAttrib[i]);
}
}
else if (parse.get("question").equals(null)){
System.out.println("question"+null);
}
}
Here I am doing for "question" only, similarly you can do other as well say "answer", "authority" in case url you have mentioned http://api.statdns.com/google.com/cname.
Hopefully it helps you with your problem..!!!!
If you are confident in the JSON not changing, a quick and dirty way to simplify your code is to use JSON Pointers.
// prefer injecting your project's ObjectMapper
private static final ObjectMapper om = new ObjectMapper();
public void parseJSON(String json) throws IOException {
JsonNode jsonNode = om.readTree(json);
String uri = new StringBuilder(jsonNode.findValue("baseURL").asText())
.append(jsonNode.findValue("param1").asText())
.append(jsonNode.findValue("param2").asText())
.toString();
initiateRESTCall(uri);
}
This becomes vulnerable if multiple apicalls entries are returned.
I don't know JACKSON library but I think it is similar to GSON. You just have to make some POJO and the library will take care of filling the fields for you.
For instance to convert your string to MyJSONClass use the following classes :
class Status {
int status;
String msg;
}
class APIClass {
String method;
String success;
String baseURL;
String param1;
String param2;
String continue_on_fail;
String add_header2;
String add_header1;
String client_id;
}
class APICall {
APIClass API;
int id;
}
class MyJSONClass {
Status status;
List<APICall> apicalls;
}
This set of classes could be transformed to JSON with JACKSON library (thanks to this stackoverflow answer) like that:
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
I want the following json ,where List<form> will have list of form_id,form_name, how can I convert this using jsonobject, I am not getting the proper json output. Please help me with this.
Json:
{
"forms": [
{ "form_id": "1", "form_name": "test1" },
{ "form_id": "2", "form_name": "test2" }
]
}
The above is the json structure that i need it for a list.Where id ,name is a list from form object
public static JSONObject getJsonFromMyFormObject(List<Form> form) {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = null;
System.out.println(form.size());
for (int i = 0; i < form.size(); i++) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("form", jsonArray);
return responseDetailsJson;
}
Facing issue here not getting output as a list
The code in the original question is close to achieving the described desired result. Just move the JSONArray instance creation outside of the loop.
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class Foo
{
public static JSONObject getJsonFromMyFormObject(List<Form> form)
{
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < form.size(); i++)
{
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);
return responseDetailsJson;
}
public static void main(String[] args)
{
List<Form> forms = new ArrayList<Form>();
forms.add(new Form("1", "test1"));
forms.add(new Form("2", "test2"));
JSONObject jsonObject = getJsonFromMyFormObject(forms);
System.out.println(jsonObject);
}
}
class Form
{
String id;
String name;
Form(String i, String n)
{
id = i;
name = n;
}
String getId()
{
return id;
}
String getName()
{
return name;
}
}
Properbly http://www.roseindia.net/tutorials/json/jsonobject-java-example.shtml will help.
According the comment from Tushar, here the extract from the aboved linked website:
Now in this part you will study how to use JSON in Java.
To have functionality of JSON in java you must have JSON-lib. JSON-lib also
requires following "JAR" files:
commons-lang.jar
commons-beanutils.jar
commons-collections.jar
commons-logging.jar
ezmorph.jar
json-lib-2.2.2-jdk15.jar
JSON-lib is a java library for that transforms beans, collections, maps, java arrays and XML to JSON and
then for retransforming them back to beans, collections, maps and
others. In this example we are going to use JSONObject class for
creating an object of JSONObject and then we will print these object
value. For using JSONObject class we have to import following package
"net.sf.json". To add elements in this object we have used put()
method. Here is the full example code of FirstJSONJava.java is as
follows:
FirstJSONJava.java
import net.sf.json.JSONObject;
public class FirstJSONJava
{
public static void main(String args[])
{
JSONObject object=new JSONObject();
object.put("name","Amit Kumar");
object.put("Max.Marks",new Integer(100));
object.put("Min.Marks",new Double(40));
object.put("Scored",new Double(66.67));
object.put("nickname","Amit");
System.out.println(object);
}
}
To run this example you have to follow these few steps as follows:
Download JSON-lib jar and other supporting Jars
Add these jars to your classpath
Create and save FirstJSONJava.java
Compile it and execute it.