I want to make a Arraylist with JSON Objects .
There is a loop which gives me JSON Objects. I want to put them into a ArrayList.
Here is the Code which gives me JSON Objects. Please let me know how to put all the values ito a ArrayList
for (int i=0; i<10; i++) {
String datapointsBodyString = "{items:[{id:" + unionUptimeMetadata.getLatencyTimeseriesIds().get(i) + ", start: " + oldestTimeString + ",end: " + now + ", granularity: 1m}]}";
JSONObject datapointsBodyObject = new JSONObject((datapointsBodyString));
HttpResponse uptimeResponse = httpService.POST("url", datapointsBodyObject.toString(), unionUptimeTimeseriesHeaders);
HttpEntity uptimeResponseEntity = uptimeResponse.getEntity();
String uptimeResponseString = EntityUtils.toString(uptimeResponseEntity);
JSONObject uptimeResponsObject = new JSONObject(uptimeResponseString);
}
Thanks in advance.
It's generally worth doing a search for common programming tasks. You could just google search "java add to list" which should result in something like:
List<JSONObject> myList = new ArrayList<>();
myList.add(uptimeResponsObject);
that should be enough for you to get it working.
Related
I have been searching all over, but I still cannot find a solution to my problem. If there is a post made already, please tell me so I can visit it. I have seen similar posts, but they follow a different JSON format than mine, so I wanted to see if it is possible and how it is possible to make it using the JSON format that will be introduced below.
Basically, what I am trying to do is get every element in a JSON file, and retrieve each element's key name and value. Both the key and the value are String values. Here is an example JSON of how I want my JSON code to look like:
{
"Variable1":"-",
"Variable2":" Test "
}
I am using the org.json library, and I would like to know if this is possible, and if it is, how can I achieve it? What I tried to do originally was put the variables under an array named "Variables", but every time I tried getting that array, it gave me an error saying that JSONObject["Variables"] is not a JSONArray. Not sure if this is caused because of a problem in the JDK or because of a problem in my code. That is, of course, a thing to discuss in another thread. So far, this is what I have (FilePath is a String variable that contains the full path to the file):
String Contents = new String((Files.readAllBytes(Paths.get(FilePath))));
JSONObject JsonFile = new JSONObject(Contents);
JSONArray VariableList = JsonFile.getJSONArray("Variables");
for (Object Item: VariableList) {
Map.Entry Item2 = (Map.Entry)Item;
System.out.println("Key: " + Item2.getKey() + ", Value: " + Item2.getValue());
}
The above code should be working if the JSON looked something like this (yes, I said should because it does not work):
{
"Variables": {
"Variable1":"-",
"Variable2":" Test "
}
}
If it is possible, how would I be able to make get the key and value using the first JSON format? If not possible, then how would I do it in an alternative way? Keep in mind, the key name is never going to the same, as the key and value will be different depending on what the user wants them to be, so that is why it is important to be able to loop through every element and get both it's key and value.
Thank you for your time and effort.
"Variables" : { ... } is a JSONObject and not a JSONArray.
For package org.json
try {
String contents = "{\"Variables\":{\"Variable1\":\"-\",\"Variable2\":\" Test \"}}";
JSONObject jsonFile = new JSONObject(contents);
JSONObject variableList = jsonFile.getJSONObject("Variables"); // <-- use getJSONObject
JSONArray keys = variableList.names ();
for (int i = 0; i < keys.length (); ++i) {
String key = keys.getString(i);
String value = variableList.getString(key);
System.out.println("key: " + key + " value: " + value);
}
} catch (Exception e) {
e.printStackTrace();
}
For package JSON.simple
String contents = new String((Files.readAllBytes(Paths.get(FilePath))));
JSONObject jsonFile = new JSONObject(contents);
JSONObject variableList = jsonFile.getJSONObject("Variables"); // <-- use getJSONObject
variableList.keySet().forEach(key -> {
Object value = jsonObj.get(key);
System.out.println("key: "+ key + ", value: " + value);
});
Good day!
I have an array of json objects like this :
[{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":0
},
{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":4
}]
For some reasons I need to split then to each element and save to storage. In the end I have many objects like
{ "senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":0
}
{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":4
}
After some time I need to combine some of them back into json array.
As I can see - I can get objects from storage, convert them with Gson to objects, out objects to a list, like this:
String first = "..."; //{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":0}
String second = "...";//{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":4}
BaseMessage msg1 = new Gson().fromJson(first, BaseMessage.class);
BaseMessage msg2 = new Gson().fromJson(second, BaseMessage.class);
List<BaseMessage> bmlist = new ArrayList<>();
bmlist.add(msg1);
bmlist.add(msg2);
//and then Serialize to json
But I guess this is not the best way. Is there any way to combine many json-strings to json array? I rtyed to do this:
JsonElement elementTm = new JsonPrimitive(first);
JsonElement elementAck = new JsonPrimitive(second);
JsonArray arr = new JsonArray();
arr.add(elementAck);
arr.add(elementTm);
But JsonArray gives me escaped string with json - like this -
["{
\"senderDeviceId\":0,
\"recipientDeviceId\":0,
\"gmtTimestamp\":0,
\"type\":4
}","
{
\"senderDeviceId\":0,
\"recipientDeviceId\":0,
\"gmtTimestamp\":0,
\"type\":0
}"]
How can I do this?
Thank you.
At the risk of making things too simple:
String first = "...";
String second = "...";
String result = "[" + String.join(",", first, second) + "]";
Saves you a deserialization/serialization cycle.
I have an array of data sent from my database - Once received, I save it in shared preferences - here is my getter:
public List getAnswerStringEdit() {
return answer_edit;
}
I save it as so:
editor.putString(Constants.ANSWER_EDIT,resp.getAnswer().getAnswerStringEdit().toString().trim());
Then retrieve it here:
String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
answerString = answerString.substring(1, answerString.length() - 1).trim();
String[] array = answerString.split(",");
Finally, I access the array as so:
et_answer1_edit.append(array[0]);
My problem is this - Say I add a questions which has a comma in the middle of it, like -
Question 1- "Why is this broke, I don't know?"
Currently, when I retrieve my question, the string is getting split, even though there are quotation marks around the whole question/answer- So in the example above, in position 0 in the array, I should have:
"Why is this broke, I don't know?"
However, instead I am getting in position 0:
Why is this broke - then position 1 as: I don't know
I know this sounds daft because clearly, I am calling for the split to happen on the comma, but I expect that at the end of the whole string object, not in the middle of it.
The retrieved JSON is as follows:
{
"result": "success",
"message": "Answer Has Been Selected",
"answer": {
"answer_edit": ["Why is this broke, I don't know?", "What is your favorite song, because I want to know"]
}
}
Any help/advice that can help me to understand what is causing this, would be really appreciated.
Dont split the string using ',' use this
JSONObject jsonObject = new JSONObject(answerString );
JSONArray jsonArray = jsonObject.getJSONObject("answer").getJSONArray("answer_edit");
Log.e("Json Array elements are","First Element : "+jsonArray.get(0)+"\nSecond Element : "+jsonArray.get(1));
String QuestionString1 = jsonArray.get(0).toString();
String QuestionString2 = jsonArray.get(1).toString();
try this one
JSONObject jsonObject = new JSONObject("your json response");
try
{
JSONObject answer= jsonObject.getJSONObject("answer");
JSONArray jsonArrayAnswerEdit = answer.getJSONArray("answer_edit");
Log.e("=>", "" + jsonArrayAnswerEdit);
for (int i = 0; i < jsonArrayAnswerEdit.length(); i++){
String que= jsonArrayAnswerEdit.getString(i);
Log.e("json", i + "=" + que);
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this
JSONObject jsonObject = new JSONObject("your json response");
try
{
JSONObject data = jsonObject.getJSONObject("answer");
JSONArray jsonArray = data.getJSONArray("answer_edit");
Log.e("=>", "" + jsonArray);
for (int i = 0; i < jsonArray.length(); i++)
{
String value = jsonArray.getString(i);
String[] parts = value.split(Pattern.quote(","));
for (int j=0; j<parts.length; j++)
{
Log.e("Answer String ", "=" + parts[j]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
OUTPUT
E/=>: ["Why is this broke, I don't know?","What is your favorite song, because I want to know"]
E/Answer String: =Why is this broke
E/Answer String: = I don't know?
E/Answer String: =What is your favorite song
E/Answer String: = because I want to know
After reading all the suggest answers, figured out a simple solution:
First I stored my answers sent from my external database as so -
final String jsonAnswers = gson.toJson (resp.getAnswer().getAnswerStringEdit());
Then saved in shared pref -
editor.putString(Constants.ANSWER_EDIT,jsonAnswers);
Next to read the answer back out:
String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
final String[] array = gson.fromJson (answerString, String[].class);
Finally, I could set my Edittext with data from the array:
et_answer1_edit.append(array[0].trim());
et_answer2_edit.append(array[1].trim());
I am new to java so sorry if my question is primitive, I have a json like :
and I want to iterate based on number of items in JSONObject:
public static void main(String[] args, int value)
{
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("/Users/.../Documents/workspace/changeReturn/bin/availableCash.json"));
for (int n=0; n < ((String) obj).length(); n++)
{
...
}
}
}
How can I get the value of obj element e.g. "2" for "$100" or "5" for "$50" and save it in objValue so that I can continue my operation listed in the code above.
There is a library for this!
JSON in Java
The library here allows us to take a JSON object, read it from an InputStream and access it.
You can download that library
here
Hopefully this helps you out, I am not sure exactly what you are trying to do.
Example:
JSONObject obj = new ("{\n" +
" \"$100\":\"2\",\n" +
" \"$50\":\"5\",\n" +
" \"$30\":\"3\",\n" +
" \"$10\":\"8\",\n" +
" \"$5\":\"4\",\n" +
"}");
obj.get("$100"); //returns 2
How can i parse an array with direct values , twice json encoded in Java, i get the data as a string and i want to get each value from the multidimensional array.
I'm kind of a noob regarding java, i managed to pull a not so elegant solution that encounters problems when i split by "," if the text inside has "," i could do it with regex but there must be a more elegant solution than this:
content = the data fetched from the api as a string
content = content.replace("\"[[", "[");
content = content.replace("]]\"", "]");
content = content.replaceAll("\\\\","");
for (String FaData : content.split("\\],\\[")) {
for (String FaDataData : FaData.split(",")) {
FaDataData.toString();
}
}
Here you have an example of how content string actually looks like when is fetched:
"[[308576,1410880665,162506,\"Bobcat\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308576.jpg\",\"Well no\",82,3,\"\"],[308592,1410883832,9479,\"undeathkiller\",2,\"http:\\\/\\\/hugelolcdn.com\\\/i\\\/308592.gif\",\"Guess the stupidity level\",89,9,\"\"],[308574,1410879991,32277,\"rady123lol\",2,\"http:\\\/\\\/hugelolcdn.com\\\/i\\\/308574.gif\",\"force of habit\",92,3,\"\"],[308624,1410897686,149704,\"Raptide7\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308624.jpg\",\"*breathing intensifies*\",114,8,\"\"],[308648,1410911037,114669,\"Huller\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308648.jpg\",\"SPOILERS: Stannis kills Dumbledore\",133,2,\"\"],[308628,1410898654,135315,\"Mig_L\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308628.jpg\",\"So badass\",117,2,\"gold\"],[308639,1410902872,62886,\"burningowl\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308639.jpg\",\"Kid's going places yo\",125,4,\"\"],[308520,1410858123,73400,\"koppie888\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308520.jpg\",\"4chan, what a beautifull place\",99,7,\"\"],[308546,1410872801,32277,\"rady123lol\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308546.jpg\",\"( \\u0361\\u00b0 \\u035c\\u0296 \\u0361\\u00b0)\",118,17,\"\"],[308486,1410846601,176339,\"AtLeastISubmit\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308486.jpg\",\"That 70's show called it.\",101,3,\"\"]]"
Assuming that you have your text in a String variable called everything, using the JSONSimple package, you can use the following code:
try {
// create a new JSONParser
JSONParser parser=new JSONParser();
// first JSON decoding
Object obj = parser.parse(everything);
// second JSON decoding
obj = parser.parse(obj.toString());
// cast the parsed JSON string to a new JSONArray
JSONArray array = (JSONArray)obj;
// loop through each line of the initial JSONArray
for (int i = 0; i < array.size(); i++){
// write the array values as a single line
System.out.println(i + " : " + array.get(i));
// parsing each line as a new JSONArray
JSONArray tmp = (JSONArray)parser.parse(array.get(i).toString());
for (int j = 0; j < tmp.size(); j++){ // iterate over the parsed values
System.out.println(i+"."+j+" : "+tmp.get(j));
}
}
} catch (ParseException ex) {
Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
}
Of course, you also have to import the following classes from the JSON package :
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
Try this
content = content.trim();
content = content.substring(0, content.length()); //gets the length of content string
content = content.replaceAll("\\/","/"); //Replaces all \/ to /
It would apply to the brackets as well.
If you're using JSON then I would suggest using a JSON library such as jackson.
ObjectMapper mapper = new ObjectMapper();
String[][] 2Darray = mapper.readValue(content, String[][].class);
But then, if you are using JSON it would be nice if the format of your data was more structured. Obviously, that depends on whether or not you have any control over the API.