how to access jsonarray using retrofit - java

how to access districtID(key) value and name(key) value using retrofit ?
this is json file...
{
"error": false,
"message": "District successfully fetched.",
"districts": [
{
"districtID": "DIS260920181",
"name": "Raipur"
},
{
"districtID": "DIS260920182",
"name": "Bilaspur"
},
{
"districtID": "DIS011020186",
"name": "korba"
},
{
"districtID": "DIS011020187",
"name": "jagdalpur"
},
{
"districtID": "DIS021020188",
"name": "surguja"
},
{
"districtID": "DIS021020189",
"name": "Mungeli"
}
]
}
Please help :(

Convert JSON Array into POJO classes and then call api using retrofit network call.

Use this link
copy your json and it gives you two model class you should put the parent class which contains error , message and districts as your output in your request. something like this
#GET("your_url")
Call<ModelExample> nameOfMethod();
And then you have list of districts. you can access to the items and districtID and name
I hope it helps you :)

for onResponse:
--------------------------
Call<ModalClass> daoCall = api.getconnectdata();
modelclass.enqueue(new Callback<ModalClass>() {
#Override
public void onResponse(Call<ModalClass> call, Response<ModalClass>
response) {
if(response.isSuccessful()){
modelclass= response.body();
List<Districts> list = modelclass.getAddData().getData();
adapter = new CustomListAdapter(getApplicationContext(),list);
listView.setAdapter(adapter);
}
}

Related

Trying to get specific data from a query response

I'm running a JUnit test, and I'm having some issues with a function where I have to get specific data from a query response. Here's a function I'm testing, note .get("data") at the end:
protected JsonNode getFunctionIds(FilterInputModel paramA) {
String paramB = "here's a query";
String idsQuery = setFunctionFieldsForQuery(paramA, paramB);
...
return Objects.requireNonNull(webClient.post()
.uri("/query")
.header(HttpHeaders.AUTHORIZATION, getSessionId())
.body(BodyInserters.fromMultipartData(queryMap))
.retrieve()
.bodyToMono(JsonNode.class)
.block())
.get("data");
}
Note that the inputModel is a class containing strings and string lists.
Here's a test I wrote. I'm getting an AssertionFailedError with it, and I vaguely know why, but I don't know how to get the right data.
#Test
void getFunctionIds() throws IOException {
Path filePath = Path.of("documents/__files/getFunctionIds.json");
String body = Files.read(filePath.toFile(), Charset.defaultCharset());
wireMockServer.stubFor(post(urlEqualTo("/api/query"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(body))
);
JsonNode jsonNode = new ObjectMapper().readValue(body, JsonNode.class);
String bodyData = new ObjectMapper().writeValueAsString(jsonNode);
JsonNode vaultData = serviceTest.getFunctionIds(inputModel);
String response = new ObjectMapper().writeValueAsString(vaultData);
assertEquals(bodyData, response);
}
Next is a query response (paramB) I got when sending it to the vault. It is stored as a String bodyData.
{
"someOtherData": ...
{
...
},
"data": [
{
"id": "V4600000002G003"
},
{
"id": "V4600000002H214"
},
{
"id": "V4600000002I001"
},
{
"id": "V4600000002J001"
},
{
"id": "V4600000002J062"
},
{
"id": "V4600000002K047"
},
{
"id": "V4600000002K071"
},
{
"id": "V4600000002K171"
}
]
}
And as I said, all I got is an AssertionFailedError, because I'm asserting the whole query response (bodyData) with just the "data" part of the JSON, which is stored in String response.
Here's the error:
Expected :{
"someOtherData"... + "data", actually the whole query response (paramB) i mentioned already.
Actual:
[
{
"id": "V4600000002G003"
},
{
"id": "V4600000002H214"
},
{
"id": "V4600000002I001"
},
{
"id": "V4600000002J001"
},
{
"id": "V4600000002J062"
},
{
"id": "V4600000002K047"
},
{
"id": "V4600000002K071"
},
{
"id": "V4600000002K171"
}
]
Is there a way to catch just the Actual part of the query response, to avoid the AssertionFailedError? That would solve my problem, obviously.

How to implement Post API JSON with Spring?

I'm having difficulty implementing a JSON to send as a POST call in Spring.
Which is the fastest and most effective way to turn this json into a java object or a map and make the call?
below is an example of a json to send:
{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {
"name": "edge-ws"
},
"spec": {
"selector": {
"matchLabels": {
"run": "edge-ws"
}
},
"replicas": 1,
"template": {
"metadata": {
"labels": {
"run": "edge-ws"
}
},
"spec": {
"containers": [
{
"name": "edge-ws",
"image": "server-tim:latest",
"imagePullPolicy": "Never",
"ports": [
{
"containerPort": 80
}
]
}
]
}
}
}
}
this and the second body that has a value (nodeport) that must be taken from a field entered by the user front end side.(page created in html)
{
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"name": "edge-ws",
"labels": {
"run": "edge-ws"
}
},
"spec": {
"type": "NodePort",
"ports": [
{
"port": 8080,
"targetPort": 80,
"nodePort": 30200,
"protocol": "TCP",
"name": "http"
}
],
"selector": {
"run": "edge-ws"
}
}
}
Both files must be sent with a single click on a button on the front end side.the first call with the first body starts and if everything is ok the second body starts
What should the class that maps objects look like? What should the controller look like instead?
They also gave me an address to call that can only be used on the machine, how can I test this call locally?
Thanks in advance!
You can use google's Gson library to convert the JsonString to Object and then use below code:
Gson gson = new Gson();
Object requestObject = gson.fromJson(jsonString, Object.class);
ResponseObject responseObject = restTemplate.postForObject(url, requestObject, ResponseObject.class);

How to pass formData for POST request in swagger.json?

In my play framework application, I have registered APIs in route file as:
POST /api/rmt-create-request controllers.Api.CreateRMTRequestForm
On action of controller, I am using following code to access formData submitted with form submit as :
public Result CreateRMTRequestForm()
{
Map<String, String[]> params = request().body().asMultipartFormData().asFormUrlEncoded();
Its working fine as API when I submit the form with forntend application.
I am trying to create APIs documentation with swagger.ui in which within swagger.json file I have written following JSON data.
"paths": {"/api/rmt-create-request": {
"post": {
"tags": [
"RMT APIs"
],
"description" : "Return newly created request data",
"operationId": "create-new-rmt-request",
"consumes": ["application/x-www-form-urlencoded"],
"parameters": [
{
"name": "rootNodeName",
"in": "formData",
"description": "Root node class name for item",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/rmt-request-data"
}
}
}
},
"default": {
"$ref": "#/components/responses/default"
}
}
}
},
While inspecting RequestHeader data, its not showing content-Type property with value 'multipart/form-data' as well as formData are not attached, which makes controller to throw null exception.
Can anyone help whats missing in swagger.json file ?
You are mixing OpenAPI 2.0 and 3.0 syntax.
In OpenAPI 3.0, request body (including form data) is defined using the requestBody keyword instead of in: formData parameters.
Also, OAS3 does not use consumes. The media types consumed by the operation are specified inside the requestBody.
"paths": {
"/api/rmt-create-request": {
"post": {
"tags": [
"RMT APIs"
],
"description": "Return newly created request data",
"operationId": "create-new-rmt-request",
"requestBody": {
"content": {
"multipart/form-data": { // or "application/x-www-form-urlencoded" - depending on what you need
"schema": {
"type": "object",
"properties": {
"rootNodeName": {
"type": "string",
"description": "Root node class name for item"
}
}
}
}
}
}
}
}
}
More information: Describing Request Body

Generic solution to GSON json object Array with a key

I am trying to find a generic solution in GSON for my project. This JSON has been problematic for me...
I have a class System
public class System{
String systemid;
String systemname;
//getter and setter
}
Rest service sends data in one of two below format, now for the second format I am handling it in a generic way as shown in last, can someone please help me to handle both the formats in a generic way in one piece of code, I am stuck on this from past two days now...
[
{
"atypes": [
{
"systemid": "123",
"systemname": "abc"
},
{
"systemid": "456",
"systemname": "def"
},
{
"systemid": "789",
"systemname": "ghi"
},
{
"id": "0123",
"name": "klm"
},
{
"systemid": "4567",
"systemname": "nop"
}
]
}
]
Or the second format
[
{
"systemid": "123",
"systemname": "abc"
},
{
"systemid": "456",
"systemname": "def"
},
{
"systemid": "789",
"systemname": "ghi"
},
{
"id": "0123",
"name": "klm"
},
{
"systemid": "4567",
"systemname": "nop"
}
]
Now I am handling the last JSON array in the below method, I want to handle both the code in one piece of generic code.
String data = client.executeCommand(Command.GET, new GenericUrl(URL), null);
System[] tList1 = JsonUtil.jsonArrayToObjectArray(data, System[].class);
which calls a generic piece of code
public static <T> T[] jsonArrayToObjectArray(String data, Class<T[]> tClass) throws Exception {
return new Gson().fromJson(data, tClass);
}
Please if someone can help me...
Edit:
This is different from identifying Json object and json array as here both are json array.

Dynamic Response from Retrofit Json to Gson Android Kotlin/Java

I have dynamic json format from rest API like this :
{
"data": {
"response_code": "success",
"value": {
"Table": [
{
"id": 5,
"username": "blahblah",
"password": "blahblah",
"role": 2,
"email": "blah#tes.com",
"tanggal_buat": "2019-01-01T00:00:00"
}
]
}
},
"meta": {
"http_status": 200
}
}
Object "value" has an object array name "Table". Table can contain value from my database dynamically depend on my query. So, Sometimes the json format will change for example :
{
"data": {
"response_code": "success",
"value": {
"Table": [
{
"id_product": 44,
"product": "blahblah",
"lot": "blahblah",
"qty": 2,
}
]
}
},
"meta": {
"http_status": 200
}
}
How to accept the json value and assign to gson directly with different subclass of "Table"
I try it in retrofit and using kotlin
override fun onResponse(call: Call<MainResp>, response: Response<MainResp>) {
mainResponse : MainResp = response.body()
}
Assuming that you have the following class among others (using sth like http://www.jsonschema2pojo.org/):
class Value {
List<Table> tables;
}
The "Table" class here cannot be completely random!
You'll need to define the possible types of "Table" e.g. Table1, Table2... TableN.
Now you can update Value class with a generic type T instead of Table and write your custom type adapter:
class Value {
List<T> tables;
}
One of the tutorials on how to write your own type adapter is here.

Categories

Resources