I want to post a json array (the users in the following json object) to a server:
// Acceptable request because the 'users' is a json array
{"users": [{"name": "Mike", "role": "editor"}, {"name":"Alice", "role": "admin"}]}
The server accepts the users as a json array not a string. But, the retrofit converts the users to a string by adding quotation marks to it like this:
// Unacceptable request because the 'users' is a string
{"users": "[{"name": "Mike", "role": "editor"}, {"name":"Alice", "role": "admin"}]"}
Here is my retrofit codes:
// interface
#FormUrlEncoded
#POST("users/store")
Call<ResponseBody> storeUser(#Field("users") JSONArray users);
// implementation
String users = "[{\"name\": \"Mike\", \"role\": \"editor\"}, {\"name\":\"Alice\", \"role\": \"admin\"}]";
JSONArray jsonArrayUsers = new JSONArray(users);
userViewModel.storeUser(jsonArrayUsers).observe(...)
So, how can I send the users as a json array to the server without allowing retrofit to convert it to string?
Related
I am trying to do JSON parsing. The JSON data is shown below, I am trying to get the "categories". I was able to JSON parse everything else, but I am not sure what does this "categories" belong to, is it a JSONObject, JSONArray, or something else? I am a newbie and self-taught, usually I am familiar that JSONArray has form of "JSONArray": {["content"]}, and the "content" is JSONObject. But in this case, "categories":["content"]. I am trying to parse this "categories", and turn it to string. Thank you for your help.
{
"results": [
{
"type": "Restaurant",
"id": "jfhuiewjkfkdljiahueijkfnlsdiejkl1484391hjk8421k",
"score": 99.9844207764,
"dist": 15.581982823437135,
"info": "search:ta:840369014527642-US",
"poi": {
"name": "RoofTop Bar",
"categorySet": [
{
"id": 184729472943
}
],
"categories": [
"pub food",
"restaurant"
]}
}]
}
This is what I have tried:
groups = new JSONArray();
groups = response.getJSONArray("results");
if (groups.length() > 0) {
JSONObject resultObject = groups.getJSONObject(0);
if (resultObject.has("poi")) {
if (resultObject.getJSONObject("poi").has("name")) {
nameResult = resultObject.getJSONObject("poi").getString("name");
} else {
nameResult = "Information is not available.";
}
if (resultObject.getJSONObject("poi").has("categories")) {
JSONObject categoriesResult;
categoriesResult = resultObject.getJSONObject("categories").toString();
}
results is an array of objects
The first object contains a property called poi
poi contains a property called categories
So using the top to bottom approach, we can arrive at
const categoriesArray = results[0].poi.categories; // gives categories as an array of strings
const categoriesString = categoriesArray.join(",") // gives categories as string, with comma separated values
I am not sure if it is the actual raw data but the poi object where the categories are contained is malformed. It is missing a closing bracket which could be causing parsing issues.
That apart, the field categories from the poi object is a list of strings I am not sure how you want to format it to a string but you could loop through them and do want you want with them.
In order to obtain them you can access them from your object with results[0].poi.categories or loop through the results before accessing the categories with result.poi.categories where result is the variable containing the currently looped result.
EDIT:
From your code sample, assuming response is a JSONObject you can do the following.
Then to obtain categories in a string without the array format, you can loop through the categories and concatenate them to a string.
String categories = resultObject.get("categories").join(", ");
I just want to POST json request(using restassured), for such json:
{
"userId": 1,
"id": 111,
"title":"test msg"
"body": "this is test msg"
}
Im defining base uri, and trying to use hashmap:
RestAssured.baseURI = "http://localhost:8888";
RestAssured.basePath = "/posts/";
Map<String, String> map = new HashMap<String, String>();
map.put("userId", 1);
map.put("id", 111);
map.put("title","test Post");
map.put("body","this is test body");
And of course its "red", because of trying put integer as string.
I'm changing to String.valueOf() for my 1 and 111 numbers,
then successfully posting request with smth like
given()
.contentType("application/json")
.body(map)
.when()
.post("/")
.then()
.statusCode(201);
But response is incorrect(comparing with needed json):
{
"id": "111",
"title": "test Post",
"body": "this is test body",
"userId": "1"
}
2 points here:
- id and userId posted as Strings
- order is incorrect
So, question:
what is the best approach in such situations, to correctly post needed request, in correct order and with int values for id and usedId?
Thanks!
What you can do is use Map<String, Object> instead of Map<String,String>.
Also, the order is not preserved for the JSON Object. You cannot and should not rely on the ordering of elements within a JSON object.
An object is an unordered set of name/value pairs.
You can check out JSON specification for more info.
I have a Java backend that accepts a json response like this:
{
"accounts": [{
"t1_Title": "title1"
}, {
"t1_Title": "title2"
}]
}
In Angular i send an array to a service to be sent to the backend.
How do i add "accounts" to an array and keep the structure above from the array which is structured like this:
(2) [Array(1), Array(1)]
0: [{…}]
1: [{…}]
length: 2
Simply bind the array value to accounts key within a new object.
Example code :
let myArray = [{ "t1_Title": "title1" }, { "t1_Title": "title2" }]
//build JSON
let obj = {accounts : myArray};
// print JSON
console.log(obj)
Currently working on an android app and I need help on how I can go about extracting the subfields within the responses field of this json object:
Currently I am doing the following to extract some of the other fields:
JSONObject json = new JSONObject(response2);
int id = json.getInt("id");
String desc = json.getString("description");
JSONObject json2 = json.getJSONObject("owner");
String username = json2.getString("userName");
You need to create logic to parse the data. Every item from the JSON string is in the JSONObject you created with
JSONObject json = new JSONObject(response2);
You're on the right track with what you're doing. Just use the corresponding methods available in JSONObject and JSONArray classes to move through the object.
Start with the main object
{ // <-- this is your main object (AKA JSONObject json = new JSONObject(response2))
"id": 1, // to pull this id use json.getInt("id");
"title": "some text here", // to pull this title use json.getString("title");
...
"owner": { // Here's the logic part, owner is itself, a JSON object. so now you must extract it and parse through it.
// to pull the "owner" JSON object, use JSONObject ownerObject = json.getJSONObject("owner");
"userId": 1, // Now use the ownerObject to pull it's values. ownerObject.getInt("userId");
"userName": "TestingUser", // to pull this userName use ownerObject.getString("userName");
...
}
...
}
If it's an array, for example:
"someJSONArray": [{ "id": 1, "userName": "TestingUser1" }, { "id": 2, "userName": "TestingUser2" }]
then you would call:
JSONArray someJSONArray = getJSONArray("someJSONArray");
// Get each object from the array.
JSONObject object1 = someJSONArray.getJSONObject(0);
JSONObject object2 = someJSONArray.getJSONObject(1);
or if the array contains a string, for example:
"someKey": [ 23, 435, 123, 6345, 123 ]
then you would call:
JSONArray someKeyArray = getJSONArray("someKey");
for (int i = 0; i < someKeyArray.length(); i++) {
// Extract the value.
int itemValue = someKeyArray.getInt(i);
}
The data is there, you just have to parse it.
I have a URL request like this:
http://localhost:8080:_dc=1367504213107&filter[0][field]=site&filter[0][data][type]=string&filter[0][data][value]=test&filter[1][field]=address&filter[1][data][type]=string&filter[1][data][value]=Columbus
This is the URL request that I get from browser.
From this URL, I need to get the filter related data as a JSON object.
Basically I have filter parameters like these in the requested URL:
filter[0][field]=site
filter[0][data][type]=string
filter[0][data][value]=test
filter[1][field]=address
filter[1][data][type]=string
filter[1][data][value]=Columbus
I am using the Spring MVC framework.
Those URL parameters aren't in JSON format. I'm not sure what your question / problem is here... can't you just read in each of those parameters from the URL and then parse the data out of the strings as you need? You could take it as a single parameter and tokenize based on a custom character, or you could just loop through all the parameters and parse each one and add them to an array.
Are you saying that you need to return the data in JSON format? Get your data using the parsed parameters as I described above, then when you have the data merely serialize that object and pass it back over the wire as the body of the response. You'll want to use a JSON serialization library like Jackson which will write the object to a string in JSON for you.
This is what that data would probably look like if it were written in JSON:
{
"filter":
[
{
"field": "site",
"data":
{
"type": "string",
"value": "test"
}
},
{
"field": "address",
"data":
{
"type": "string",
"value": "Columbus"
}
}
]
}
Java code that translates from the above JSON to your-format:
JSONObject root = new JSONObject(json);
JSONArray filters = root.getJSONArray("filter");
for (int i = 0; i < filters.length(); i++)
{
JSONObject filter = filters.getJSONObject(i);
String field = filter.getString("field");
JSONObject data = filter.getJSONObject("data");
String dataType = data.getString("type");
String dataValue = data.getString("value");
System.out.println("filter[" + i + "][field]=" + field);
System.out.println("filter[" + i + "][data][type]=" + dataType);
System.out.println("filter[" + i + "][data][value]=" + dataValue);
}
Your data format does not appear to be standard, so you will have to parse it yourself.