How can I convert a List object in Java to a JSON object?
For example, how can I convert this:
List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2):
...
To this JSON:
{
"List" : [1, 2, ...]
}
Thank you!
If you want just to convert the list to json, you can use Gson:
List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
String json = new Gson().toJson(myList);
If you want that the key will be "List", you need to create a object with a member that call List and then convert it.
If you need to convert to String use the com.fasterxml.jackson.databind.ObjectMapper
Ex:
List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(myList);
System.out.println("result = " + json);
//System.out.println(json);
} catch (JsonProcessingException e) {
//
}
Related
I am writing data to a JSON file using a for loop, my question is will all the data be written to the file or a new .json file will be created every time?
List<String> list = new ArrayList<String>();
list.add("abc");
list.add("def");
list.add("xyz");
for (String name : list) {
JSONObject obj = new JSONObject();
obj.put("Name:", name);
try (FileWriter file = new FileWriter("C:\\Users\\elements.json")) {
file.write(obj.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
Please update your code like this.
...
FileWriter file = new FileWriter("C:\Users\elements.json")
for (String name : list) {
JSONObject obj = new JSONObject();
obj.put("Name:", name);
file.write(obj.toJSONString());
}
file.flush();
...
Otherwise, please use string variable to store all json as one string variable and write the string variable to file at once.
Instead, you can use Jackson's ObjectMapper to map the entire list object.
List<String> list = new ArrayList<>();
list.add("abc");
list.add("def");
list.add("xyz");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(new File("elements.json"), list);
strResponse = {"GetCitiesResult":["1-Vizag","2-Hyderbad","3-Pune","4-Chennai","9-123","11-Rohatash","12-gopi","13-Rohatash","14-Rohatash","10-123"]}
JSONObject json = new JSONObject(strResponse);
// get LL json object
String json_LL = json.getJSONObject("GetCitiesResult").toString();
Now i want to convert the json string to List in andriod
Please make sure your response String is correct format, if it is, then try this:
try {
ArrayList<String> list = new ArrayList<String>();
JSONObject json = new JSONObject(strResponse);
JSONArray array = json.getJSONArray("GetCitiesResult");
for (int i = 0; i < array.length(); i++) {
list.add(array.getString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
Simply using Gson library you can convert json response to pojo class.
Copy the json string to create pojo structure using this link: http://www.jsonschema2pojo.org/
Gson gson = new Gson();
GetCitiesResult citiesResult = gson.fromJson(responseString, GetCitiesResult.class);
It will give the GetCitiesResult object inside that object you get a list of your response like
public List<String> getGetCitiesResult() {
return getCitiesResult;
}
Call only citiesResult.getGetCitiesResult(); it will give a list of cities.
You can also use this library com.squareup.retrofit2:converter-gson:2.1.0
This piece of code did the trick
List<String> list3 = json.getJSONArray("GetCitiesResult").toList()
.stream()
.map(o -> (String) o)
.collect(Collectors.toList());
list3.forEach(System.out::println);
And printed:
1-Vizag
2-Hyderbad
3-Pune
4-Chennai
9-123
11-Rohatash
12-gopi
13-Rohatash
14-Rohatash
10-123
below is code:
private void parse(String response) {
try {
List<String> stringList = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("GetCitiesResult");
for (int i=0; i <jsonArray.length(); i++){
stringList.add(jsonArray.getString(i));
}
Log.d ("asd", "--------"+ stringList);
} catch (Exception e) {
e.printStackTrace();
}
}
Hope it will help.
Output is when print list :
--------[1-Vizag, 2-Hyderbad, 3-Pune, 4-Chennai, 9-123, 11-Rohatash, 12-gopi, 13-Rohatash, 14-Rohatash, 10-123]
Ok you must know first something about JSON
Json object is be {// some attribute}
Json Array is be [// some attribute]
Now You have
{"GetCitiesResult":["1-Vizag","2-Hyderbad",
"3-Pune","4-Chennai","9-123","11-Rohatash",
"12-gopi","13-Rohatash","14-Rohatash","10-123"]}
That`s Means you have JSON array is GetCitiesResult
which have array of String
Now Try this
JSONObject obj = new JSONObject(data);
JSONArray loadeddata = new JSONArray(obj.getString("GetCitiesResult"));
for (int i = 0; i <DoctorData.length(); i++) {// what to do here}
where data is your String
I have a Sring s (JSON array) [{"Phonetype":"Pre","Phone":"918282311"},{"Phonetype":"pre","Phone":"918333222"}]
and now i want to convert this string to JSON array of the JSON objects.
in my code i only can create a JSONrray of objects...
#Override
public ArrayList<TelephoneNumber> convertToAttribute(String s) {
ArrayList<TelephoneNumber> list = new ArrayList<TelephoneNumber>();
JSONParser parser = new JSONParser();
JSONArray arr = null;
try {
arr = (JSONArray) parser.parse(s);
}
catch (ParseException e) {
e.printStackTrace();
}
for (JSONObject jo: arr)
{
System.out.println("obj " +jo.get("Phone");
}
//create a list
return list;
}
how create a JsonArray of JsonObjects?
Consider using Gson to parse json values and use FieldNamingPolicy on a GsonBuilder to get a Gson object that handles upper camel case names correctly:
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
Type listType = new TypeToken<ArrayList<TelephoneNumber>>() {}.getType();
List<TelephoneNumber> numbers = gson.fromJson(jsonArray, listType);
I'd recommend taking a look at Gson. It is a series of Java classes written by The Google Overlords that handles serializing and deserializing JSON from and to Java classes.
So, making a few assumptions about what your TelephoneNumber class looks like, you should be able to do this:
Type listType = new TypeToken<ArrayList<TelephoneNumber>>() {
}.getType();
ArrayList<TelephoneNumber> yourList = new Gson().fromJson(s, listType);
Then return yourList....
I have a json file.
{
"data" : [
"my/path/old",
"my/path/new"
]
}
I need to conver it to ArrayList of String. How to do it using Jackson library?
UPD:
My code:
Gson gson = new Gson();
JsonReader reader = new JsonReader(new InputStreamReader(FileReader.class.getResourceAsStream(file)));
List<String> list = (ArrayList) gson.fromJson(reader, ArrayList.class);
for (String s : list) {
System.out.println(s);
}
And my exception:
Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 1
My new update
UPD2:
Gson gson = new Gson();
Type list = new TypeToken<List<String>>(){}.getType();
JsonReader reader = new JsonReader(new InputStreamReader(FileReader.class.getResourceAsStream(file)));
List<String> s = gson.fromJson(reader, list);
System.out.println(s);
You've tagged Jackson but are using Gson in your example. I'm going to go with Jackson
String json = "{\"data\":[\"my/path/old\",\"my/path/new\"]}"; // or wherever you're getting it from
Create your ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Read the JSON String as a tree. Since we know it's an object, you can cast the JsonNode to an ObjectNode.
ObjectNode node = (ObjectNode)mapper.readTree(json);
Get the JsonNode named data
JsonNode arrayNode = node.get("data");
Parse it into an ArrayList<String>
ArrayList<String> data = mapper.readValue(arrayNode.traverse(), new TypeReference<ArrayList<String>>(){});
Printing it
System.out.println(data);
gives
[my/path/old, my/path/new]
I have a List<class> that I would like to convert into a json object and then traverse the data out of the json object.
If this were just a List<String> I could just do something like:
JSONObject obj = new JSONObject();
List<String> sList = new ArrayList<String>();
sList.add("val1");
sList.add("val2");
obj.put("list", sList);
Then I could traverse the list like:
JSONArray jArray = obj.getJSONArray("list");
for (int ii = 0; ii < jArray.size(); ii++)
System.out.println(jArray.getString(ii));
The problem with using the class is that I need to have access to data within each class element of my List<class> and I don't know how to encode that / traverse it into JSON. Any help would be greatly appreciated.
Call getJSONObject() instead of getString(). That will give you a handle on the JSON object in the array and then you can get the property off of the object from there.
For example, to get the property "value" from a List<SomeClass> where SomeClass has a String getValue() and setValue(String value):
JSONObject obj = new JSONObject();
List<SomeClass> sList = new ArrayList<SomeClass>();
SomeClass obj1 = new SomeClass();
obj1.setValue("val1");
sList.add(obj1);
SomeClass obj2 = new SomeClass();
obj2.setValue("val2");
sList.add(obj2);
obj.put("list", sList);
JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
System.out.println(jArray.getJSONObject(ii).getString("value"));
Let us assume that the class is Data with two objects name and dob which are both strings.
Initially, check if the list is empty. Then, add the objects from the list to a JSONArray
JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<Data>();
//if List not empty
if (!sList.isEmpty()) {
//Loop index size()
for(int index = 0; index < sList.size(); index++) {
JSONObject eachData = new JSONObject();
try {
eachData.put("name", sList.get(index).getName());
eachData.put("dob", sList.get(index).getDob());
} catch (JSONException e) {
e.printStackTrace();
}
allDataArray.put(eachData);
}
} else {
//Do something when sList is empty
}
Finally, add the JSONArray to a JSONObject.
JSONObject root = new JSONObject();
try {
root.put("data", allDataArray);
} catch (JSONException e) {
e.printStackTrace();
}
You can further get this data as a String too.
String jsonString = root.toString();
This is how I do it using Google Gson. I am not sure, if there are a simpler way to do this (with or without an external library).
Type collectionType = new TypeToken<List<Class>>() {
}.getType();
String gsonString = new Gson().toJson(objList, collectionType);
You could use a JSON serializer/deserializer like flexjson to do the conversion for you.
Just to update this thread, here is how to add a list (as a json array) into JSONObject.
Plz substitute YourClass with your class name;
List<YourClass> list = new ArrayList<>();
JSONObject jsonObject = new JSONObject();
org.codehaus.jackson.map.ObjectMapper objectMapper = new
org.codehaus.jackson.map.ObjectMapper();
org.codehaus.jackson.JsonNode listNode = objectMapper.valueToTree(list);
org.json.JSONArray request = new org.json.JSONArray(listNode.toString());
jsonObject.put("list", request);