I want to create a JSON data with two objects in an array
String message = "{ "animal" : [{"name":"alice", "type":"cat"}, {"name":"john", "type":"dog"}, {"name":"peter", "type":"bird"} ] }";
But this will make some errors and cannot run in eclipse
How can I resolve it
You have to escape double quotes with backslashes as shown below:
String message = "{ \"animal\" : [{\"name\":\"alice\", \"type\":\"cat\"}, {\"name\":\"john\", \"type\":\"dog\"}, {\"name\":\"peter\", \"type\":\"bird\"} ] }";
Eclipse has an option "Escape text when pasting into a string literal" (Preferences->Java->Editor->Typing) that copy-paste multi-line text into String literals will result in quoted new lines. Please note that after enabling this feature you still have to first write two quotation marks and then paste your text inside those marks.
Adding the the code samples to parse your json data.
package com.stackoverflow.answer;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonParserExample {
public static void main(String[] args) {
String message = "{ \"animal\" : [{\"name\":\"alice\", \"type\":\"cat\"}, {\"name\":\"john\", \"type\":\"dog\"}, {\"name\":\"peter\", \"type\":\"bird\"} ] }";
JSONObject messageJson = new JSONObject(message);
JSONArray animals = messageJson.getJSONArray("animal");
int n = animals.length();
for (int i = 0; i < n; ++i) {
JSONObject animal = animals.getJSONObject(i);
System.out.println(String.format("animal.%d.name: %s", i, animal.getString("name")));
System.out.println(String.format("animal.%d.type: %s", i, animal.getString("type")));
}
}
}
Hope you are clear now. It's too late. I'm going to sleep. Happy coding!!!
Related
I have an integer value, say int id whose value i get runtime by getter function.
I want to replace this value of id in place of "VALUE" from .json like as follows
{
"id":"VALUE",
"name": "Name updated",
"description": "description Updated",
"active": false
}
I found following way to replace it if id is String,
String str = "myJson.json";
str.replace("\"VALUE\"", "\"id\"");
How can i use int id in above function with this format "\"id\"" ?
Any other solution are welcome.
EDIT:
String str = "myJson.json";
is wrong way to get json content into String.
You can do it with simple regex replace, e.g.:
public static void main(String[] args) {
String value = "{\"id\":\"VALUE\",\"name\": \"Name updated\",\"description\": \"description Updated\",\"active\": false}";
int id = 5;
value = value.replaceAll("\"VALUE\"", String.valueOf(id));
System.out.println(value);
}
Using org.json library you can assign it to JSON Object and Use the put method:
JSONObject jsonObject= new JSONObject(YOUR_STRING);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
JSONObject id= jsonArray.getJSONObject(0).getJSONObject("id");
person.put("VALUE", id);
regex replace may create some issue by replace someother matching string .
I did in following way.
To replace content of Json file need to convert contents in to String. I did this with help of following function.
public static String loadJson(String jsonFileName) throws IOException {
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(jsonFileName);
return IOUtils.toString(stream);
}
Then declare a String variable,
String editedJson = loadJson(TEST_SET + "myJson.json");
editedJson.replace("VALUE", "" + id);
I have been trying, and struggling, to parse arrays contained in a JSON file, into a Java ArrayList. Could I please have some advise on how to proceed with this? Please find an example JSON Array below:
[
{
"id": "USER_ID_HERE",
"dateTime": "DATE_TIME_HERE",
"message": "WRITE_SOMETHING_MEANINGFUL_HERE",
"latitude": 27.99999
"longitude": 26.33333333
}
]
My current Java code can be found below - how can I parse in the array from the JSON file?
public class ParseJSON {
ArrayList <Tweet> = new ArrayList <Tweet>();
class Tweet{
public String id;
public String message;
public String dateTime;
public double latitude;
public double longitude;
}
JSONObject js = new JSONObject("tweets");
JSONArray jsarray = js.getJSONArray("tweets");
int size = jsarray.length();
for (int i = 0; i < size; i++)
{
JSONObject tweet = jsarray.getJSONObject(i);
System.out.println("tweet: " + tweet.getString("id"));
System.out.println("tweet: " + tweet.getString("message"));
System.out.println("tweet: " + tweet.getString("dateTime"));
System.out.println("tweet: " + tweet.getDouble("latitude"));
System.out.println("tweet: " + tweet.getDouble("longitude"));
}
t = new tweet( tweet.getString("id")) & ( tweet.getString("message")) & ( tweet.getString("datetime")) & ( tweet.getDouble("latitude")) & ( tweet.getDouble("longitude"));
Tweet.list.add(t);
}
}
Thank you in advance for any advice.
You seem to be pretty close to the required functionality, some issues though:
Firstly, the code you want to execute is not in a method. Try to add a "main" method to your ParseJSON class.
Your Tweet class doesn't have a custom constructor, so you won't be able to create Tweet objects and populate their attributes with a constructor as you attempt to do further down.
Your ArrayList<Tweet> member variable doesn't have an identifier.
For:
t = new tweet( tweet.getString("id")) & ( tweet.getString("message")) & ( tweet.getString("datetime")) & ( tweet.getDouble("latitude")) & ( tweet.getDouble("longitude"));
You want to do this for each element of the JSON array, so move the line inside your for loop. Also, the parameters should be separated by a comma, not an ampersand. You should also use a capital T for new Tweet (to refer to the constructor you should have created).
For:
Tweet.list.add(t);
This currently expects list to be a (static) member of Tweet. Try changing this to access the name you should have given to your ArrayList. This line should also be inside the for loop for the same reason as above.
I'm using GSON for parsing JSON response.
Unfortunately the WebApi on the server has quite untypical JSON objects.
I need to parse Attachments array from this JSON (there can be more attachments):
{"htmlMessage":"text","Attachments":{"8216096_0":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg","contentDisposition":"attachment","size":86070}}}
Where 8216096_0 is attachments id.
I can't do it with Gson (or I don't know how) so I'm trying to do it with JSONObjects:
// parse attachments
JSONObject attachmentsJson = result.getJSONObject("Attachments");
Then I have one JSONObject with an array of attachments, but I don't know how to get them to the ArrayList from JSONObject because the key value isn't static but generated id..
Thank you
//EDIT:
Thanks to all guys for helping! My final solution looks like this especially thanks to #Jessie A. Morris and his final answer!
List<AttachmentModel> attachmentsList = new ArrayList<AttachmentModel>();
for( Map.Entry<String, JsonElement> attachment : attachments.entrySet()) {
AttachmentModel attachmentModel = new AttachmentModel();
attachmentModel = gson.fromJson(attachment.getValue().getAsJsonObject().toString(), AttachmentModel.class);;
attachmentModel.setmUid(attachment.getKey());
attachmentsList.add(attachmentModel);
}
Okay, I've changed my example a little bit and am certain that this does work correctly (I just tested it):
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by jessie on 14-07-09.
*/
public class TestGson {
private static String JSON = "{\"htmlMessage\":\"text\",\"Attachments\":{\"8216096_0\":{\"content\":null,\"filename\":\"plk.jpg\",\"contentType\":\"image/jpeg\",\"contentDisposition\":\"attachment\",\"size\":86070}}}\n";
public static void main(String[] args) {
JsonObject json = new JsonParser().parse(JSON).getAsJsonObject();
JsonObject attachments = json.getAsJsonObject("Attachments");
List<JsonObject> attachmentsList = new ArrayList<JsonObject>();
for( Map.Entry<String, JsonElement> attachment : attachments.entrySet()) {
attachmentsList.add(attachment.getValue().getAsJsonObject());
}
System.out.println("attachmentsList at the end? " + attachmentsList);
}
}
I'm not completely sure if this really works:
final Map<String,JSONObject> attachmentsJson = (Map<String,JSONObject>) jsonArray.getJSONObject("Attachments");
for(String attachmentId : attachmentsJson.keySet()) {
final JSONObject attachmentJson = attachmentsJson.get(attachmentId);
}
The "Attachments" obj in your example is not an array.
Json arrays are denoted by [....].
"Attachments" is a Json object holding an inner object called "8216096_0".
so to get the inner values do as follows:
JSONObject attachmentsJson = result.getJSONObject("Attachments");
JSONObject inner = attachmentsJson.getJSONObject("8216096_0");
// and interrogate the inner obj:
String content = inner.getString("content");
String filename = inner.getString("filename");
Finally, and for example sake, I will add the code for processing a (real) Json array:
{"htmlMessage":"text",
"Attachments":[{"8216096_0":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg",
"contentDisposition":"attachment","size":86070}},
{"8216096_1":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg",
"contentDisposition":"attachment","size":86070}},
]
}
It will go like this:
JSONArray attachmentsJson = result.getJSONObject("Attachments");
int len = attachmentsJson.length();
for (int i = 0; i < len; i++) {
JSONObject elem = attachmentsJson.getJSONObject(i); // <------ get array element
JSONObject inner = elem.getJSONObject("8216096_0");
// and interrogate the inner obj:
String content = inner.getString("content");
String filename = inner.getString("filename");
}
..Or similar, depending on your Json's exact format.
I'm wondering, can I have text like this:
ps:mandatory' child of Input command functions
Properties
ps:Source:
f47437
ps:Created:
2010-09-03T11:38:02.629Z
ps:ChangedBy:
F47437
ps:Changed:
2011-09-07T07:51:10.864Z
In JSON format. The problem is there ..that the file includes tens of thousands of that text type and they're like tree family. And my point is to convert it to JSON saving the same tree logic. I just wanted to ask for my own knowledge.
Do you mean like this?
{
"ps:mandatory": "Properties",
"ps:Source:": "f47437",
"ps:Created:": "2010-09-03T11:38:02.629Z",
"ps:ChangedBy:": "F47437",
"ps:Changed:": "2011-09-07T07:51:10.864Z"
}
It's important to remember that JSON is unordered so you will most likely lose the order of the tags when storing it in JSON. If order is important, consider another file format.
The following code will turn your data above into JSON. Compiles and works:
import org.json.*;
public class CreateMyJSON
{
public static void main(String[] args)
{
String testData = "ps:mandatory\nProperties\n\nps:Source:\n f47437\n\nps:Created:\n 2010-09-03T11:38:02.629Z\n\nps:ChangedBy:\n F47437\n\nps:Changed:\n 2011-09-07T07:51:10.864Z\n\n";
CreateMyJSON cmj = new CreateMyJSON();
System.out.println(cmj.getJSONFromString(testData));
}
public String getJSONFromString(String theData)
{
JSONObject jso = new JSONObject();
//no error checking, but replacing double returns
//to make this simpler
String massagedData = theData.replaceAll("\n\n", "\n");
String[] splits = massagedData.split("\n");
for(int i = 0; i < splits.length; i++)
{
jso.put(splits[i].trim(), splits[++i].trim());
}
return jso.toString();
}
}
This question already has answers here:
Converting JSON data to Java object
(14 answers)
Closed 9 years ago.
I have a Java Rest API #PUT. Which is receiving the json data as shown in below format
["name1,scope1,value1","name2,scope2,value2"]
I am getting this value in my Java API method as
(String someList)
someList will contain ["name1,scope1,value1","name2,scope2,value2"]
How to get these values ("name1,scope1,value1" and "name2,scope2,value2") in String array?
Using the org.json package, this would do (assuming response as String in responseString):
JSONArray myJSON = new JSONArray(responseString);
String[] myValues = new String[myJSON.length];
for(int i=0; i<myValues.length; i++) {
myValues[i] = myJSON.getString(i);
}
If you then want to split up the strings in myValues[] using ',' as a separator, you can do:
String[] innerArray = myValues[i].split(",");
An example JSON code :
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
class JsonDecodeDemo
{
public static void main(String[] args)
{
JSONParser parser=new JSONParser();
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
System.out.println("s = " + s);
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println("The 2nd element of array");
System.out.println(array.get(1));
System.out.println();
JSONObject obj2 = (JSONObject)array.get(1);
System.out.println("Field \"1\"");
System.out.println(obj2.get("1"));
s = "{}";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,]";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,,2]";
obj = parser.parse(s);
System.out.println(obj);
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
}
}
You can refer to this.
You could put the parts into an array of String with just one line:
String[] parts = someList.replaceAll("^\\[\"|\"\\]$", "").split("\",\"");
The call to replaceAll() strips off the leading and trailing JSON adornment and what's left is split on what appears between the target parts, ie ","
Note that due to the flexible nature of valid json, it would be safer to use a JSON library than this "string based" approach. Use this only if you can't use a json library.