How to pass json array under request body using simply json - java

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;
}
}

Related

How to use gson for getstring of json?

I am new to use gson.
I found a lots of tutorial there I can learn of gson but there are using recylerview and model file.
JsonObjectRequest request = new JsonObjectRequest(LoginUrl, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG , String.valueOf(response));
try {
String statusObject = response.getString("status");
String msgObject = response.getString("msg");
if (statusObject.equals("200")) {
JSONArray jsonArray = response.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject managerResponse= jsonArray.getJSONObject(i);
// userIdObject = managerResponse.getString("user_id");
// String nameObject = managerResponse.getString("name");
// String emailObject = managerResponse.getString("email");
// String mobileObject = managerResponse.getString("mobile");
// String postobject = managerResponse.getString("post");
// pojectObject = managerResponse.getString("project");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
Here I can get data from jsonrequest using volley but unable to do that same process using volley and gson. Is there any way to use gson?
Thank You.
Update
My JSON Response
{
"status": "200",
"msg": "Successfully",
"response": [
{
"user_id": "1",
"name": "HEMANT OJHA",
"email": "hemguna#gmail.com",
"mobile": "9584919991",
"address1": "C92, PALLAWI NAGAR BABADIYA KALAN",
"user": "admin",
"api_token": "admin"
}
]
}
Generating POJO class from JSON
// Considering your response consists of json objects & json array
// Create a POJO class for your response with the link above
{
"keyOne": 1,
"keyTwo": "Some Value",
"someArray": [{
"key": "Value"
},
{
"key": "Value"
}
]
}
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ExampleClass {
#SerializedName("keyOne")
#Expose
private int keyOne;
#SerializedName("keyTwo")
#Expose
private String keyTwo;
#SerializedName("someArray")
#Expose
private List<SomeArray> someArray = null;
public int getKeyOne() {
return keyOne;
}
public void setKeyOne(int keyOne) {
this.keyOne = keyOne;
}
public String getKeyTwo() {
return keyTwo;
}
public void setKeyTwo(String keyTwo) {
this.keyTwo = keyTwo;
}
public List<SomeArray> getSomeArray() {
return someArray;
}
public void setSomeArray(List<SomeArray> someArray) {
this.someArray = someArray;
}
}
// Parsing JSON response with GSON
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ExampleClass resultObj = gson.fromJson(jsonObject.toString(), ExampleClass.class);
int keyOneValue = resultObj.getKeyOne() // First JSON Object
// Getting String value
String keyTwoValue = resultObj.getKeyTwo() // Second JSON Object
List<SomeArray> yourJSONArray = resultObj.getSomeArray() // Getting JSON Array contents
// Depending on JSON response that you've updated in your question
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ExampleClass resultObj = gson.fromJson(jsonObject.toString(),ExampleClass.class);
String status = resultObj.getStatus();
String msg = resultObj.getMsg();
List<Response> responseList = resultObj.getResponse();
The best way to use for entire app is create a Utils class and use it for conversion.
GsonUtils.java
// This Class is useful for mapping Json into Java Objects and vice versa.
public class GsonUtils {
private static final Gson gson = new Gson();
// This will Convert Java Objects into JSON String...
public static String toGson(Object object) {
return gson.toJson(object);
}
// Gives Java Objects from JSON
public static <T> T fromGson(String json, Class<T> type) {
return gson.fromJson(json, type);
}
public static JsonArray fromGson(String json) {
return new JsonParser().parse(json).getAsJsonArray();
}
}
Now convert any json to and from POJO via,
POJO pojoObj = GsonUtils.toGson(POJO.class);
Try this
JSON response
String str = new Gson().toJson(response)

Volley post method JSONArray

anyone can suggest me how to POST volley JSONArray body like
{
"mobileNo":"9876543210",
"dobDocuments" : [
"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/dob_proofs/DOB Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/dob_proofs/DOB Proof2.jpg"
],
"educationDocuments" : [
"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/edu_proofs/EDU Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/edu_proofs/EDU Proof2.jpg"
],
"addressDocuments" : [
"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/add_proofs/ADD Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/add_proofs/ADD Proof2.jpg"
]
}
for this instance I've Hashmap which contains this array data.
I searched lot but not getting proper solution for this type.
Thank you..!
Try this
JSONObject sendObject = new JSONObject();
try {
JSONArray dobDocuments = new JSONArray();
dobDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
dobDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
JSONArray educationDocuments = new JSONArray();
educationDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
educationDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
JSONArray addressDocuments = new JSONArray();
addressDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
addressDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
sendObject.put("dobDocuments", dobDocuments);
sendObject.put("educationDocuments", addressDocuments);
sendObject.put("addressDocuments", addressDocuments);
sendObject.put("mobileNo", "9876543210");
} catch (JSONException e) {
}
Log.e("JSONObject",sendObject.toString());
OUTPUT
{
"dobDocuments": ["https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray", "https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray"],
"educationDocuments": ["https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray", "https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray"],
"addressDocuments": ["https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray", "https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray"],
"mobileNo": "9876543210"
}
If you want to use model classes and comfortable with GSON.
Add this to build.gradle
implementation 'com.google.code.gson:gson:2.8.4'
Create class for your request/response
class MyRequest {
private String mobileNo;
private String[] dobDocuments;
private String[] educationDocuments;
private String[] addressDocuments;
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String[] getDobDocuments() {
return dobDocuments;
}
public void setDobDocuments(String[] dobDocuments) {
this.dobDocuments = dobDocuments;
}
public String[] getEducationDocuments() {
return educationDocuments;
}
public void setEducationDocuments(String[] educationDocuments) {
this.educationDocuments = educationDocuments;
}
public String[] getAddressDocuments() {
return addressDocuments;
}
public void setAddressDocuments(String[] addressDocuments) {
this.addressDocuments = addressDocuments;
}
}
Now create JSONObject
try {
MyRequest myRequest = new MyRequest();
myRequest.setMobileNo("9876543210");
myRequest.setDobDocuments(new String[] {"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/dob_proofs/DOB Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/dob_proofs/DOB Proof2.jpg"});
myRequest.setEducationDocuments(new String[]{ "http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/edu_proofs/EDU Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/edu_proofs/EDU Proof2.jpg"});
myRequest.setAddressDocuments(new String[]{"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/add_proofs/ADD Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/add_proofs/ADD Proof2.jpg"});
JSONObject jsonObject = new JSONObject(new Gson().toJson(myRequest));
Log.e("jsonObject", jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}

Building a Json String in java?

I am trying to build a json string in java but I am a bit confused as how I should go about it. This is what I tried so far.
String jsonString = new JSONObject()
.put("JSON1", "Hello World!")
.put("JSON2", "Hello my World!")
.put("JSON3", new JSONObject()
.put("key1", "value1")).toString();
System.out.println(jsonString);
The output is :
{"JSON2":"Hello my World!","JSON3":{"key1":"value1"},"JSON1":"Hello World!"}
The Json I want is as follows :-
{
"data":{
"nightclub":["abcbc","ahdjdjd","djjdjdd"],
"restaurants":["fjjfjf","kfkfkfk","fjfjjfjf"],
"response":"sucess"
}
}
How should I go about it?
You will need to use JSONArray and JsonArrayBuilder to map these json arrays.
This is the code you need to use:
String jsonString = new JSONObject()
.put("data", new JSONObject()
.put("nightclub", Json.createArrayBuilder()
.add("abcbc")
.add("ahdjdjdj")
.add("djdjdj").build())
.put("restaurants", Json.createArrayBuilder()
.add("abcbc")
.add("ahdjdjdj")
.add("djdjdj").build())
.put("response", "success"))
.toString();
You can use gson lib.
First create pojo object:
public class JsonReponse {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public class Data {
private String reponse;
private List<String> nightclub;
private List<String> restaurants;
public String getReponse() {
return reponse;
}
public void setReponse(String reponse) {
this.reponse = reponse;
}
public List<String> getNightclub() {
return nightclub;
}
public void setNightclub(List<String> nightclub) {
this.nightclub = nightclub;
}
public List<String> getRestaurants() {
return restaurants;
}
public void setRestaurants(List<String> restaurants) {
this.restaurants = restaurants;
}
}
}
and next complite data and generate json:
JsonReponse jsonReponse = new JsonReponse();
JsonReponse.Data data = jsonReponse.new Data();
data.setReponse("sucess");
data.setNightclub(Arrays.asList("abcbc","ahdjdjd","djjdjdd"));
data.setRestaurants(Arrays.asList("fjjfjf","kfkfkfk","fjfjjfjf"));
jsonReponse.setData(data);
Gson gson = new Gson();
System.out.println(gson.toJson(jsonReponse));

Java - Get multiple JSON values and turn into String

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());

Json parsing with nested array using Gson

I have not seen an (answered) example on the web which discusses this kind of nested-json-array.
JSON to be parsed:
{
"Field": {
"ObjectsList": [
{
"type": "Num",
"priority": "Low",
"size": 3.43
},
{
"type": "Str",
"priority": "Med",
"size": 2.61
}
]
}
}
I created a class for each 'level' of nested json block. I want to be able to parse the contents of the "ObjectList" array.
Can anyone help me to parse this JSON using Gson in Java?
Any hints or code-snippets would be greatly appreciated.
My approach is the following:
public static void main (String... args) throws Exception
{
URL jsonUrl = new URL("http://jsonUrl.com") // cannot share the url
try (InputStream input = jsonUrl.openStream();
BufferedReader buffReader = new BufferedReader (new InputStreamReader (input, "UTF-8")))
{
Gson gson = new GsonBuilder().create();
ClassA classA = gson.fromJson(buffReader, ClassA.class);
System.out.println(classA);
}
}
}
class ClassA
{
private String field;
// getter & setter //
}
class ClassB
{
private List<ClassC> objList;
// getter & setter //
}
clas ClassC
{
private String type;
private String priority;
private double size;
// getters & setters //
public String printStr()
{
return String.format(type, priority, size);
}
}
The following snippet and source file would help you:
https://github.com/matpalm/common-crawl-quick-hacks/blob/master/links_in_metadata/src/com/matpalm/MetaDataToTldLinks.java#L17
private static ParseResult NO_LINKS = new ParseResult(new HashSet<String>(), 0);
private JsonParser parser;
public static void main(String[] s) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(s[0]));
MetaDataToTldLinks metaDataToTldLinks = new MetaDataToTldLinks();
while (reader.ready()) {
String[] fields = reader.readLine().split("\t");
ParseResult outboundLinks = metaDataToTldLinks.outboundLinks(fields[1]);
System.out.println(tldOf(fields[0]) + " " + outboundLinks.links);
}
}
public MetaDataToTldLinks() {
this.parser = new JsonParser();
}
public ParseResult outboundLinks(String jsonMetaData) {
JsonObject metaData = parser.parse(jsonMetaData.toString()).getAsJsonObject();
if (!"SUCCESS".equals(metaData.get("disposition").getAsString()))
return NO_LINKS;
JsonElement content = metaData.get("content");
if (content == null)
return NO_LINKS;
JsonArray links = content.getAsJsonObject().getAsJsonArray("links");
if (links == null)
return NO_LINKS;
Set<String> outboundLinks = new HashSet<String>();
int numNull = 0;
for (JsonElement linke : links) {
JsonObject link = linke.getAsJsonObject();
if ("a".equals(link.get("type").getAsString())) { // anchor
String tld = tldOf(link.get("href").getAsString());
if (tld == null)
++numNull;
else
outboundLinks.add(tld);
}
}
return new ParseResult(outboundLinks, numNull);
}
public static String tldOf(String url) {
try {
String tld = new URI(url).getHost();
if (tld==null)
return null;
if (tld.startsWith("www."))
tld = tld.substring(4);
tld = tld.trim();
return tld.length()==0 ? null : tld;
}
catch (URISyntaxException e) {
return null;
}
}
public static class ParseResult {
public final Set<String> links;
public final int numNull;
public ParseResult(Set<String> links, int numNull) {
this.links = links;
this.numNull = numNull;
}
}
How about this snippet?:
if (json.isJsonArray()) {
JsonArray array = json.getAsJsonArray();
List<Object> out = Lists.newArrayListWithCapacity(array.size());
for (JsonElement item : array) {
out.add(toRawTypes(item));
}
}

Categories