Java - Get multiple JSON values and turn into String - java

How would I get all the "name" values and turn them into a String?
So for example if I'd do the following:
System.out.println(value[1]);
It would print out name1.
Here is what I have so far:
JSON:
[
{
"name":"name1"
},
{
"name":"name2",
"changedToAt":1470659096000
},
{
"name":"name3",
"changedToAt":1473435817000
}
]
Java code:
try {
String UUID = p.getUniqueId().toString();
String slimUUID = UUID.replace("-", "");
InputStream in = new URL("https://api.mojang.com/user/profiles/" + slimUUID + "/names").openStream();
String json = IOUtils.toString(in);
IOUtils.closeQuietly(in);
try {
JSONParser parser = new JSONParser();
JSONObject jsonparse = (JSONObject) parser.parse(json);
//get "name" values and turn into String
} catch (ParseException e) {
System.out.println(e.getMessage());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}

You need to iterate over array and accumulate all name values into array of Strings.
So below is working source code:
JsonArray jsonObject = new JsonParser()
.parse(json)
.getAsJsonArray();
List<String> names = new ArrayList<>();
for (JsonElement jsonElement : jsonObject) {
names.add(jsonElement.getAsJsonObject().get("name").getAsString());
}
//now you can use as you wish, by index
System.out.println(names.get(1));//returns "name2"

Using the URL from your comment and Java 8 Stream API I've built this main method:
public static void main(final String[] args) throws ParseException, MalformedURLException, IOException {
final String url = "https://api.mojang.com/user/profiles/c8570e47605948d3a3cbe3ec3a681cc0/names";
final InputStream in = new URL(url).openStream();
final String json = IOUtils.toString(in);
IOUtils.closeQuietly(in);
final JSONParser parser = new JSONParser();
final JSONArray jsonparse = (JSONArray) parser.parse(json);
System.out.println(jsonparse);
System.out.println();
final List<String> names = (ArrayList<String>) jsonparse.stream().map((obj) -> {
final JSONObject object = (JSONObject) obj;
return (String) object.getOrDefault("name", "");
}).peek(System.out::println).collect(Collectors.toList());
}

Try My library: abacus-common. All the above can be replaced with:
List<Map<String, Object>> resp = HttpClient.of("https://api.mojang.com/user/profiles/" + slimUUID + "/names").get(List.class);
List<String> names = resp.stream().map(m -> (String) (m.get("name"))).collect(Collectors.toList());
By the way, if slimUUID is equal to: UUID.randomUUID().toString().replaceAll("-", ""). It's be simplified:
List<Map<String, Object>> resp = HttpClient.of("https://api.mojang.com/user/profiles/" + N.guid()+ "/names").get(List.class);
List<String> names = resp.stream().map(m -> (String) (m.get("name"))).collect(Collectors.toList());

Related

Java: How do I create this JSON Array Structure using GSON

I want to create a JSON array structure like this or append an object to the structure
{ "user" : [
{"name" : "user1", "email": "user1#gmail"},
{"name": "user2", "email": "user2#gmail"}
]
}
I'm using GSON to write this into a file
public void appendToObject(File jsonFile, String key, String value) {
Objects.requireNonNull(jsonFile);
Objects.requireNonNull(key);
Objects.requireNonNull(value);
if (jsonFile.isDirectory()) {
throw new IllegalArgumentException("File can not be a directory!");
}
try {
JsonObject node = readOrCreateNew(jsonFile);
JsonArray userArray = new JsonArray();
userArray.add(user(key,value));
node.add("user", userArray);
FileWriter writer = new FileWriter(jsonFile)
gson.toJson(node, writer);
}catch (Exception e)
{
Log.d("display1", "appendToObject: error"+e.getLocalizedMessage());
e.printStackTrace();
}
}
private JsonObject user(String user, String password){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", user);
jsonObject.addProperty("password", password);
return jsonObject;
}
private JsonObject readOrCreateNew(File jsonFile) throws IOException {
if (jsonFile.exists() && jsonFile.length() > 0) {
try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile))) {
return gson.fromJson(reader, JsonObject.class);
}
}
return new JsonObject();
}
Here's the code with suggestions integrated and with reading and writing JSON file functions
but im getting "user1":"{\"values\":[null,\"user13\",\"useremail13\"]}"}
how to structure it so that I get the desired output
I omitted some your code in appendToObject. But the meaning should be clear.
public void appendToObject(File jsonFile, String key, String value) {
...
JsonObject node = readOrCreateNew(jsonFile);
JsonObject newUser = user(key, value);
JsonElement user = node.get("user");
if (user != null && user.isJsonArray()){
((JsonArray) user).add(newUser);
} else {
JsonObject root = new JsonObject();
node.add("user", createArray(newUser));
}
...
}
private JsonObject createUserArray(JsonObject ... objects){
JsonArray userArray = new JsonArray();
for (JsonObject user : objects) {
userArray.add(user);
}
return userArray;
}
private JsonObject user(String email, String name){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", name);
jsonObject.addProperty("email", email);
return jsonObject;
}

How to pass json array under request body using simply json

I am using below code to automate REST API.
Please help me to understand how can I put whole json data for sample data mentioned below as the input has arrays whereas till now I used flat jsons without arrays
Method Dummy()
{
RestAssured.baseURI ="http://mydummyURL";
RequestSpecification request = RestAssured.given();
JSONObject requestParams = new JSONObject();
requestParams.put("id", "THAILAND"); //Issue is with this code
request.header("Content-Type", "application/json");
request.body(requestParams.toJSONString());
Response response = request.post("/EndPoint");
}
where the json body looks like this
{
"tag1": "value1",
"tag2": "value2",
"tag3": {
"tag31": "value31",
"tag32": "value32"
},
"tag4": [{
"domainName": "ABC",
"domainId": "123ABC123",
"domainGUID": "TestMyDomain"
},
{
"domainName": "XYZ",
"domainId": "123XYZ123",
"domainGUID": "TestMyDomain"
}
]
}
ArrayList<JSONObject> array= new ArrayList<JSONObject>();
JSONObject json= new JSONObject();
try {
json.put("key", "value");// your json
} catch (JSONException e) {
e.printStackTrace();
}
array.add(json);
String printjsonarray= array.toString();// pass this into the request
ObjectMapper mapper = new ObjectMapper();
//Create a Java Class for the variables inside array.
JsonArrayData tag4paramVal1 = new JsonArrayData("ABC","123ABC123","TestMyDomain");
JsonArrayData tag4paramVal2 = new JsonArrayData("XYZ","123XYZ123","TestMyDomain");
Object[] tag4ValArray = {tag4paramVal1,tag4paramVal2};
String reqJson = null;
List<String> tag4Data = new ArrayList<String>();
for(Object obj:tag4ValArray){
reqJson = mapper.writeValueAsString(obj);
System.out.println(reqJson);
tag4Data.add(reqJson);
}
System.out.println(tag4Data);
HashMap<String,List<String>> finalReq = new HashMap<String,List<String>>();
finalReq.put("\"tag4\":",tag4Data);
String finalreqString = finalReq.toString();
System.out.println(finalreqString);
finalreqString = finalreqString.replace('=', ' ');
System.out.println(finalreqString);
//Use the above String as a parameter to POST request. You will get your desired JSON array .
//JsonArrayData class code
public class JsonArrayData {
String domainName;
String domainId;
String domainGUID;
public JsonArrayData(String domainName,String domainId,String domainGUID){
this.domainName = domainName;
this.domainId = domainId;
this.domainGUID = domainGUID;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
public String getDomainGUID() {
return domainGUID;
}
public void setDomainGUID(String domainGUID) {
this.domainGUID = domainGUID;
}
}

parse json values using java json parser

I have a josn like this.From this how can i retrive platfrom and version values using java
code
public static void main(String[] args)
throws org.json.simple.parser.ParseException {
try {
// read the json file
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
josn
{
"France24":[
{
"platform":"Linux",
"version":"12.3",
}
],
"Seloger":[
{
"platform":"windows",
"version":"8",
}
],
"Marmiton":[
{
"platform":"mac",
"version":"10.1",
}
]
}
List<String> platformLst = new ArrayList<String>();
List<String> versionLst = new ArrayList<String>();
JSONArray array = obj.getJSONArray("France24");
for(int i = 0 ; i < array.length() ; i++){
JSONObject obj = array.getJSONObject(i);
versionLst.add(obj.getString("platform"));
platformLst .add(obj.getString("version"));
}
Existing Question
Example
Simple Json Tutorial Link
JSONArray jArray = jsonObject.getJSONArray("France24");
JSONObject france24Object = jArray.get(0);
String platform = france24Object.getString("platform");
String version = france24Object.getString("version");
Similarly, replace France24 with Seloger and Marmiton and repeat.
Like that:
JSONObject france = jsonObject.getJsonArray("France24").getJsonObject(0);
String platform = france.getString("platform");
String version = france.getString("version");

How to convert list data into json in java

I have a function which is returning Data as List in java class. Now as per my need, I have to convert it into Json Format.
Below is my function code snippet:
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
return cartList;
}
I tried To convert into json by using this code but it is giving type mismatch error as function is of type List...
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
Gson gson = new Gson();
// convert your list to json
String jsonCartList = gson.toJson(cartList);
// print your generated json
System.out.println("jsonCartList: " + jsonCartList);
return jsonCartList;
}
Please help me resolve this.
Using gson it is much simpler. Use following code snippet:
// create a new Gson instance
Gson gson = new Gson();
// convert your list to json
String jsonCartList = gson.toJson(cartList);
// print your generated json
System.out.println("jsonCartList: " + jsonCartList);
Converting back from JSON string to your Java object
// Converts JSON string into a List of Product object
Type type = new TypeToken<List<Product>>(){}.getType();
List<Product> prodList = gson.fromJson(jsonCartList, type);
// print your List<Product>
System.out.println("prodList: " + prodList);
public static List<Product> getCartList() {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", "1");
formDetailsJson.put("name", "name1");
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format
return cartList;
}
you can get the data in the following form
{
"forms": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}
Try these simple steps:
ObjectMapper mapper = new ObjectMapper();
String newJsonData = mapper.writeValueAsString(cartList);
return newJsonData;
ObjectMapper() is com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper();
i wrote my own function to return list of object for populate combo box :
public static String getJSONList(java.util.List<Object> list,String kelas,String name, String label) {
try {
Object[] args={};
Class cl = Class.forName(kelas);
Method getName = cl.getMethod(name, null);
Method getLabel = cl.getMethod(label, null);
String json="[";
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
if(i>0){
json+=",";
}
json+="{\"label\":\""+getLabel.invoke(o,args)+"\",\"name\":\""+getName.invoke(o,args)+"\"}";
//System.out.println("Object = " + i+" -> "+o.getNumber());
}
json+="]";
return json;
} catch (ClassNotFoundException ex) {
Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
System.out.println("Error in get JSON List");
ex.printStackTrace();
}
return "";
}
and call it from anywhere like :
String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber");
Try like below with Gson Library.
Earlier Conversion List format were:
[Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]]
and here the conversion source begins.
//** Note I have created the method toString() in Product class.
//Creating and initializing a java.util.List of Product objects
List<Product> productList = (List<Product>)productRepository.findAll();
//Creating a blank List of Gson library JsonObject
List<JsonObject> entities = new ArrayList<JsonObject>();
//Simply printing productList size
System.out.println("Size of productList is : " + productList.size());
//Creating a Iterator for productList
Iterator<Product> iterator = productList.iterator();
//Run while loop till Product Object exists.
while(iterator.hasNext()){
//Creating a fresh Gson Object
Gson gs = new Gson();
//Converting our Product Object to JsonElement
//Object by passing the Product Object String value (iterator.next())
JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class);
//Creating JsonObject from JsonElement
JsonObject jsonObject = element.getAsJsonObject();
//Collecting the JsonObject to List
entities.add(jsonObject);
}
//Do what you want to do with Array of JsonObject
System.out.println(entities);
Converted Json Result is :
[{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}]
Hope this would help many guys!
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<String> ls =new ArrayList<String>();
for(product cj:cities.getList()) {
ls.add(cj);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", cj.id);
formDetailsJson.put("name", cj.name);
jsonArray.put(formDetailsJson);
}
responseDetailsJson.put("Cities", jsonArray);
return responseDetailsJson;
You can use the following method which uses Jackson library
public static <T> List<T> convertToList(String jsonString, Class<T> target) {
if(StringUtils.isEmpty(jsonString)) return List.of();
return new ObjectMapper().readValue(jsonString, new ObjectMapper().getTypeFactory().
constructCollectionType(List.class, target));
} catch ( JsonProcessingException | JSONException e) {
e.printStackTrace();
return List.of();
}
}
if response is of type List , res.toString() is simply enough to convert to json or else we need to use
ObjectMapper mapper = new ObjectMapper();
String jsonRes = mapper.writeValueAsString(res);

How to modify values of JsonObject / JsonArray directly?

Once i have parsed a JSON String into a GSON provided JsonObject class, (assume that i do not wish to parse it into any meaningful data objects, but strictly want to use JsonObject), how am i able to modify a field / value of a key directly?
I don't see an API that may help me.
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonObject.html
Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
This works for modifying childkey value using JSONObject.
import used is
import org.json.JSONObject;
ex json:(convert json file to string while giving as input)
{
"parentkey1": "name",
"parentkey2": {
"childkey": "test"
},
}
Code
JSONObject jObject = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);
output:
{
"parentkey1": "name",
"parentkey2": {
"childkey": "data1"
},
}
Since 2.3 version of Gson library the JsonArray class have a 'set' method.
Here's an simple example:
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));
array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));
Another approach would be to deserialize into a java.util.Map, and then just modify the Java Map as wanted. This separates the Java-side data handling from the data transport mechanism (JSON), which is how I prefer to organize my code: using JSON for data transport, not as a replacement data structure.
It's actually all in the documentation.
JSONObject and JSONArray can both be used to replace the standard data structure.
To implement a setter simply call a remove(String name) before a put(String name, Object value).
Here's an simple example:
public class BasicDB {
private JSONObject jData = new JSONObject;
public BasicDB(String username, String tagline) {
try {
jData.put("username", username);
jData.put("tagline" , tagline);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUsername () {
String ret = null;
try {
ret = jData.getString("username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public void setUsername (String username) {
try {
jData.remove("username");
jData.put("username" , username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getTagline () {
String ret = null;
try {
ret = jData.getString("tagline");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static JSONObject convertFileToJSON(String fileName, String username, List<String> list)
throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
JSONObject json = new JSONObject();
String jsonStr = new String(Files.readAllBytes(Paths.get(fileName)));
json = new JSONObject(jsonStr);
System.out.println(json);
JSONArray jsonArray = json.getJSONArray("users");
JSONArray finalJsonArray = new JSONArray();
/**
* Get User form setNewUser method
*/
//finalJsonArray.put(setNewUserPreference());
boolean has = true;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
finalJsonArray.put(jsonObject);
String username2 = jsonObject.getString("userName");
if (username2.equals(username)) {
has = true;
}
System.out.println("user name are :" + username2);
JSONObject jsonObject2 = jsonObject.getJSONObject("languages");
String eng = jsonObject2.getString("Eng");
String fin = jsonObject2.getString("Fin");
String ger = jsonObject2.getString("Ger");
jsonObject2.put("Eng", "ChangeEnglishValueCheckForLongValue");
System.out.println(" Eng : " + eng + " Fin " + fin + " ger : " + ger);
}
System.out.println("Final JSON Array \n" + json);
jsonArray.put(setNewUserPreference());
return json;
}

Categories