Convert JSON into List of Object property (Java) - java

I have simple json which looks like this :
[
{
"id":"0",
"name":"Bob",
"place":"Colorado",
},
{
"id":"1",
"name":"John",
"place":"Chicago",
},
{
"id":"2",
"name":"Marry",
"place":"Miami",
}
]
What I want is using Java to create list of strings (List<String>) that contains all 'names'. I have some experience using Gson and I think about something like:
Gson gson = new Gson();
String[] stringArray= gson.fromJson(jsonString, " ".class);
The problem with this method is that I should create some POJO class which I didn`t in this case. Is it any way I can achieve it without creating separate class with this 'name' property ?

Using Jackson to parse, and Java 8 Streams API for extracting only the name field; the following may help you:
// Your string
jsonString = "[{ \"id\":\"0\", \"name\":\"Bob\", \"place\":\"Colorado\" }, { \"id\":\"1\", \"name\":\"John\", \"place\":\"Chicago\"}, { \"id\":\"2\", \"name\":\"Marry\", \"place\":\"Miami\" }]";
// using Jackson to parse
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getTypeFactory();
List<MyInfo> myObjectList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, MyInfo.class));
// Java 8 Collections
List<String> nameList = myObjectList.stream().map(MyInfo::getName).collect(Collectors.toList());
Beware, it implies the usage of a MyInfo class representing your a Java class in which Json objects of yours would fit in.

You can use JSONArray to get value from key 'name'. Like this:
JSONArray jSONArray = new JSONArray(yourJson);
List<String> list = new ArrayList<>();
for (int i = 0; i < jSONArray.length(); i++) {
JSONObject object = (JSONObject) jSONArray.get(i);
String value = object.getString("name");
System.out.println(value);
list.add(value);
}

You may try the following code snippet,
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
List<String> ls = new ArrayList<String>();
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONParser jsonParse = new JSONParser();
String str = "[{\"id\": \"0\",\"name\": \"Bob\",\"place\": \"Colorado\"},"
+ "{\"id\": \"1\",\"name\": \"John\",\"place\": \"Chicago\"},"
+ "{\"id\": \"2\",\"name\": \"Marry\",\"place\": \"Miami\"}]";
try {
jsonArr= (JSONArray) jsonParse.parse(str); //parsing the JSONArray
if(jsonArr!=null){
int arrayLength =jsonArr.size(); //size is 3 here
for(int i=0;i<arrayLength;i++){
jsonObj = (JSONObject) jsonParse.parse(jsonArr.get(i).toString());
ls.add(jsonObj.get("name").toString()); //as we need only value of name into the list
}
System.out.println(ls);
}
} catch (ParseException e) {
e.printStackTrace();
}catch(Exception e1){
e1.printStackTrace();
}
As you have array, use JSONArray and used jsonParse to avoid any parsing error.
I have used json-simple API to acheive the above.

Related

How to remove extra escaping quote characters of JsonObject created through Javax

I use javax to create JsonObject and JsonArray from my List<String> and I have a list of Json objects that i want to put in a JsonObject through a JsonArray
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (String Obj : listOfJsonDfObjects)
jsonArray.add(summaryObj); //{"a":"b"},{"c":"d"}
// this line introduces extra escaping quotes like this {"\"a\"":"\"b\""},{"\"c\"":"\"d\""}
javax.json.JsonObject data = Json.createObjectBuilder()
.add("data", jsonArray.build()).build();
How to avoid these extra quotes escaping characters?
Thanks
You say you have a list of JSON objects, but you really have a list of JSON-formatted strings. To add them to a JsonArray, you need to parse each one into the JSON object model:
public class JsonTest {
public static void main(String[] args) {
List<String> listOfJsonDfObjects = List.of(
"{\"a\":\"b\"}",
"{\"c\":\"d\"}"
);
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (String summaryObj : listOfJsonDfObjects) {
JsonReader parser = Json.createReader(new StringReader(summaryObj));
jsonArray.add(parser.readObject());
}
JsonObject data = Json.createObjectBuilder()
.add("data", jsonArray.build()).build();
System.out.println(data); // {"data":[{"a":"b"},{"c":"d"}]}
}
}
Using Gson
Gson gson = new Gson();
String json = gson.toJson(listOfJsonDfObjects);
//check json
System.out.println(json);
json = json.replaceAll("\\\\", "");
json = json.replaceAll("\"\\{", "{");
json = json.replaceAll("\\}\"", "}");
//valid json now
System.out.println(json);
A more secure way (to avoid altering original data)
//concatenate objects in list with comma
String json = String.join(",", listOfJsonDfObjects);
//convert to pseudo array
json = "[" + json + "]";
//convert pseudo json array to pseudo json object
json = "{\"data\":" + json + "}";
//cast to json object
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
System.out.println(jsonObject);

JSON Input for POST request to call REST API

How do i convert a model Person to match the input?
Person p = new Person(name, age, amountInBank);
(name in String, age in int and amountInBank in double)
I want my JSON Input to be as follow:
{
"ID": "H123",
"list" : [
{
"name" : "ally",
"age": 18,
"amountInBank": 200.55
}
]
}
Currently my code to call REST API is:
JSONObject jsonInput= new JSONObject();
jsonInput.put("ID", "H123");
//put in list input in JSON -> HELP NEEDED
Resource resource = client.resource(URL HERE);
resource.contentType(MediaType.APPLICATION_JSON);
resource.accept(MediaType.APPLICATION_JSON);
ClientResponse cliResponse = resource.post(jsonInput);
Tried many ways but couldn't achieve the expected input for list in JSON format. Please help
Method 1:
ArrayList<Map<String, Object>> list = new ArrayList<>();
list.add(p);
jsonInput.put("list" , list);
Method 2:
JSONArray jsonArr = new JSONArray();
jsonArr.add(p);
jsonInput.put("list", jsonArr);
Method 3:
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "ally");
map.put("age", 18);
map.put("amountInBank" : 255.55);
jsonInput.put("list", map);
Safest bet is to use a well known library for the marshalling, such as Jackson. It is able to convert your object to JSON format with the following:
ObjectMapper mapper = new ObjectMapper(); //from Jackson library
Person p = new Person(name, age, amountInBank); //your POJO
String jsonString = mapper.writeValueAsString(p); //convert
Source: https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
There are also other alternatives, this is just a personal preference as Jackson is very widely used and well documented.
If you're trying to get a list of array JSON objects then just substitute the Person object with List<Person> and try to marshall that.
Try the code below
val listJsonArry = JsonArray()
var jsonObject = JsonObject()
jsonObject.add("name", "ally")
jsonObject.add("age", "18")
jsonObject.add("amountInBank", "200.55")
listJsonArry.add(jsonObject)
PostData
var postjsonObject = JsonObject()
postjsonObject.add("ID", "H123")
postjsonObject.add("list", listJsonArry)
First you have to create JSONObject and put ID, H123.
Then you have to create Another JSONObject wich will accept a person details.
pass another JSONObject to JSONArray and path JSONArray to JSONObjct. check the code
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject(); // first json object
jsonObject.put("ID", "H123"); put ids.
JSONArray jsonArray = new JSONArray(); // prepear json array
Person person = new Person("Ally", 18, 200.55); // create person object and populate it with data
// JSONObject jsonObject = new JSONObject(person); you can pass your person directly to JSONObject constructor and it will deparse it base on your getter methods in person class.
JSONObject jsonObject1 = new JSONObject(); // then pass person data to Json object
jsonObject1.put("name", person.getName());
jsonObject1.put("age", person.getAge());
jsonObject1.put("amountInBank", person.getAmountInBank());
jsonArray.put(jsonObject1); // pass json object to json array
jsonObject.put("list", jsonArray); // and pass json array to json object
System.out.println();
try (FileWriter file = new FileWriter("person.json")) {
file.write(jsonObject.toString(5));
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
above code will produce output
{
"ID": "H123",
"list": [{
"name": "Ally",
"amountInBank": 200.55,
"age": 18
}]
}
if you need to do that from database, more like there will be a lot of persons. put person object and json object in some kind of loop and populate it as long as you want. then pass it to json array and json array to jsonobject to have many records.

Retrieve just one field from JSON string in Java

Is there a way to just one field from the JSON string? My code is as follows:
Object obj = parser.parse(resp);
System.out.println(obj);
JSONArray array = new JSONArray();
array.add(obj);
JSONObject obj2 = (JSONObject)array.get(0); //Getting NPE here
//Object obj3 = obj2.get("data");
System.out.println("Data: " + obj2.get("data"));
//System.out.println("Email: " + obj3.get("email_address"));
I'm using the following libraries
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
From the response string resp, I just need data.email_address. I am unable to find a way to do it.
So if this is your input:
{
"data": {
"email_address": "example#example.com"
}
}
You first will need to make it a JSONObject:
JSONObject object = (JSONObject) new JSONParser().parse(json);
And then you can get data, another JSONObject:
JSONObject data = (JSONObject) object.get("data")
And from your data Object you can get email_address:
String email = data.get("email_address").toString();
If your input is an array of users, like this:
{
"users": [
{
"data": {
"email_address": "example#example.com"
}
},
{
"data": {
"email_address": "exapmle2#example2.com"
}
}
]
}
You can get it the same way:
JSONObject object = (JSONObject) new JSONParser().parse(json);
JSONArray users = (JSONArray) object.get("users");
JSONObject user0 = (JSONObject) users.get(0);
JSONObject user0data = (JSONObject) user0.get("data");
String email = user0data.get("email_address").toString();
First parse the whole JSON into an Object. Then get an array called users, from that array, get index 0. From that Object, get data, and then email_address
The other option is to use jsonpath.
Using the same Json blob as Lorant:
{
"data": {
"email_address": "example#example.com"
}
}
You would use the following expression.
$.data.email_address
Or if it was an array, simply.
$.users.[data].email_address
An online tool can be used to experiment and learn the syntax, but if you know xpath it should be somewhat familiar already.
import org.json.JSONObject;
JSONObject json = new JSONObject(record);
json.getString("fieldName"));

How to convert a snake_case JSON to nested JSON in java?

I have few cases where I want to convert a snake_case JSON to nested JSON
e.g.
{
"snake_case": {
"test": "value"
}
}
to
{
"snake": {
"case": {
"test": "value"
}
}
}
Is there any way to do this in java other then manually parsing the strings with _ or there any libraries are there in java?
Consider your JSON data as String:
String strjson="{snake_case: {test: value}}";
then
JSONObject jj=new JSONObject(strjson);
JSONObject jfinal=new JSONObject();
Iterator<String> itr=jj.keys();
while(itr.hasNext())
{
String key=itr.next();
if(key.contains("-"))
{
JSONObject jkey=jj.getJSONObject(key);
JSONObject jnew=new JSONObject();
jnew.put(key.split("-")[1],jkey);
jfinal.put(key.split("-")[0],jnew);
}
}
you can get the output in jfinal.
You could BSON to achieve this. Here is the code you would use.
//import java.util.ArrayList;
//import org.bson.Document;
//Declare three json object
Document root= new Document();
Document rootSnake = new Document();
Document rootSnakeCase = new Document();
//Add value to the most nested object
rootSnakeCase.append("test","value");
//combine the objects together
if (!rootSnakeCase.isEmpty()){
rootSnake.append("case",rootSnakeCase);
}
if (!rootSnake.isEmpty()){
root.append("snake",rootSnake);
}
//output code
System.out.println(root.toJson());

Convert normal Java Array or ArrayList to Json Array in android

Is there any way to convert a normal Java array or ArrayList to a Json Array in Android to pass the JSON object to a webservice?
If you want or need to work with a Java array then you can always use the java.util.Arrays utility classes' static asList() method to convert your array to a List.
Something along those lines should work.
String mStringArray[] = { "String1", "String2" };
JSONArray mJSONArray = new JSONArray(Arrays.asList(mStringArray));
Beware that code is written offhand so consider it pseudo-code.
ArrayList<String> list = new ArrayList<String>();
list.add("blah");
list.add("bleh");
JSONArray jsArray = new JSONArray(list);
This is only an example using a string arraylist
example key = "Name" value = "Xavier" and the value depends on number of array you pass in
try
{
JSONArray jArry=new JSONArray();
for (int i=0;i<3;i++)
{
JSONObject jObjd=new JSONObject();
jObjd.put("key", value);
jObjd.put("key", value);
jArry.put(jObjd);
}
Log.e("Test", jArry.toString());
}
catch(JSONException ex)
{
}
you need external library
json-lib-2.2.2-jdk15.jar
List mybeanList = new ArrayList();
mybeanList.add("S");
mybeanList.add("b");
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google Gson is the best library http://code.google.com/p/google-gson/
This is the correct syntax:
String arlist1 [] = { "value1`", "value2", "value3" };
JSONArray jsonArray1 = new JSONArray(arlist1);
For a simple java String Array you should try
String arr_str [] = { "value1`", "value2", "value3" };
JSONArray arr_strJson = new JSONArray(Arrays.asList(arr_str));
System.out.println(arr_strJson.toString());
If you have an Generic ArrayList of type String like ArrayList<String>. then you should try
ArrayList<String> obj_list = new ArrayList<>();
obj_list.add("value1");
obj_list.add("value2");
obj_list.add("value3");
JSONArray arr_strJson = new JSONArray(obj_list));
System.out.println(arr_strJson.toString());
My code to convert array to Json
Code
List<String>a = new ArrayList<String>();
a.add("so 1");
a.add("so 2");
a.add("so 3");
JSONArray jray = new JSONArray(a);
System.out.println(jray.toString());
output
["so 1","so 2","so 3"]
Convert ArrayList to JsonArray
: Like these [{"title":"value1"}, {"title":"value2"}]
Example below :
Model class having one param title and override toString method
class Model(
var title: String,
var id: Int = -1
){
override fun toString(): String {
return "{\"title\":\"$title\"}"
}
}
create List of model class and print toString
var list: ArrayList<Model>()
list.add("value1")
list.add("value2")
Log.d(TAG, list.toString())
and Here is your output
[{"title":"value1"}, {"title":"value2"}]

Categories

Resources