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.
Related
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.
I am very new to hapi FHIR, I am trying to encode the request in following format.
CoverageEligibilityRequest coverageEligibilityRequest = new CoverageEligibilityRequest();
Patient patient = new Patient().addIdentifier(new Identifier().setType(getPatientIdentifierCodeableConcept()).setSystem("http://www.abc.xyz").setValue("123"));
coverageEligibilityRequest.setPatient(new Reference(patient));
Above code is java snippet for populating the patient in CoverageEligibilityRequest.
{
"resourceType": "Bundle",
"type": "batch",
"entry": [ {
"resource": {
"resourceType": "CoverageEligibilityRequest",
"id": "7890",
"contained": [ {
"resourceType": "Patient",
"id": "1",
"identifier": [ {
"type": {
"coding": [ {
...
...
}
But I want the request should be of following format
{
"resourceType": "Bundle",
"type": "batch",
"entry": [ {
"resource": {
"resourceType": "CoverageEligibilityRequest",
"id": "7890",
"patient": {
"type": "Patient",
"identifier": {
"type": {
"coding": [ {
...
...
} ]
},
where I want to omit contained with actual string?
FHIR doesn't generally let you express an entire graph of objects as a single resource, so if you're trying to send a Patient resource as part of a CoverageEligibilityRequest resource, the only way you can do that is by setting the patient in the contained field. The CoverageEligibilityResource.patient field is defined as a Reference type and so can only contain the data allowed by a Reference data type and not arbitrary data.
It seems like what you actually want to do is to add a Patient to the HAPI FHIR server and a CoverageEligibilityRequest resource that references the patient. The right way to do this in FHIR is to construct a single batch or transaction bundle containing both of the resources. Basically, you want to construct a Bundle that looks something like this:
{
"resourceType": "Bundle",
"type": "batch",
"entry": [ {
"resource": {
"resourceType": "Patient",
"id": "1",
"identifier": [ {
"type": {
"coding": [ {
...
}
}, {
"resource": {
"resourceType": "CoverageEligibilityRequest",
"id": "7890",
"patient": "Patient/1",
...
The easiest way to construct something similar in HAPI FHIR would be to use a transaction bundle like this:
IGenericClient client = ...
CoverageEligibilityRequest coverageEligibilityRequest = new CoverageEligibilityRequest();
Patient patient = new Patient().addIdentifier(new Identifier().setType(getPatientIdentifierCodeableConcept()).setSystem("http://www.abc.xyz").setValue("123"));
coverageEligibilityRequest.setPatient(new Reference(patient));
client.transaction().withResources(patient, coverageEligibilityRequest);
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);
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.
I need to build a below JSON programmatically. But,need a elegant way to convert from Java object to JSON. so that, i can avoid string builder to build the below JSON.
I aware of that, sometimes,I have array of parameters for the specific key while building JSON.
Please share the generic way to solve that.
Please share some thoughts to this.
{
"tropo": [
{
"ask": {
"attempts": 3,
"say": [
{
"value": "Hi.",
"event": "timeout"
},
{
"value": "Hello",
"event": "nomatch:1"
},
{
"value": "Hello2",
"event": "nomatch:2"
},
{
"value": "Satheesh",
"voice": "veronica"
}
],
"choices": {
"value": "Yes(1,Yes),No(2,No)",
"mode": "ANY"
},
"voice": "veronica",
"recognizer": "en-us",
"timeout": 8,
"name": "year",
"minConfidence": 39,
"required": true
}
},
{
"on": {
"next": "https://test.app.com/WAP2/",
"event": "continue"
}
},
{
"on": {
"next": "https://test.app.com/WAP2/",
"event": "incomplete"
}
},
{
"on": {
"next": "",
"event": "hangup"
}
}
]
}
As paulsm4 said, I'd have a look at gson. It's easy to use, you can find a lot of example of how it works all over the web (official user guide).
Example:
Employee employee = new Employee();
employee.setId(1);
employee.setFirstName("Lokesh");
employee.setLastName("Gupta");
employee.setRoles(Arrays.asList("ADMIN", "MANAGER"));
Gson gson = new Gson();
System.out.println(gson.toJson(employee));
Output:
{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"]}
From howtodoinjava.com/'s Google Gson Tutorial : Convert Java Object to / from JSON.