How to get json value using GSON from json tree - java

I have a json such as below
{
"apiVersion": "v1",
"metadata": {
"status": {
"statusCode": 0
},
},
"stuff": [
{
"name": {
"text": "red"
},
"properties": [
{
"attributes": {
"shade": "dark"
},
"component": {
"id": "BA1",
}
"type": "Color"
}
]
},
{
"name": {
"text": "Toyota Camry"
},
"properties": [
{
"attributes": {},
"component": {
"id": "MS",
},
"type": "Vehicle"
}
]
},
]
}
I'm using GSON to parse the results like this:
Gson gson = new Gson();
JsonObject json = (JsonObject) gson.fromJson(in, JsonObject.class);
System.out.println(json.get("apiVersion").getAsString());
I can get the apiVersion but don't know how to get elements that are inside the json tree. For example, type...what if I want to output all the different type..in this case Color and Vehicle

I must be missing something here, but why can't you nest calls to getJsonObject? For example, to get the status code:
System.out.println(json.getAsJsonObject("metadata")
.getAsJsonObject("status")
.get("statusCode").getAsInt());

You can create an object in that matter and to parse the json to it (with GSON):
ParsedObject parsedObject = new Gson().fromJson(json, ParsedObject.class);
public class ParsedObject {
#SerializedName(value = "apiVersion")
private String mApiVersion;
#SerializedName(value = "metadata")
private Metadata mMetadata;
}

Related

Extract specific data from json object and store them in a list

I´m new to the world of json format. I have Json info stored in a json object and I only want to extract name key values in a list. At least I have one user and sometimes more than one user. Extraction using Java or Groovy.
{
"reviewers": [
{
"user": {
"name": "name1.n1",
"emailAddress": "example#example.com"
},
"role": "REVIEWER"
},
{
"user": {
"name": "name2.n2",
"emailAddress": "example2#example.com"
},
"role": "REVIEWER"
}
]
}
basic groovy+json doc here: https://groovy-lang.org/json.html
import groovy.json.JsonSlurper
def json = '''{
"reviewers": [
{
"user": {
"name": "name1.n1",
"emailAddress": "example#example.com"
},
"role": "REVIEWER"
},
{
"user": {
"name": "name2.n2",
"emailAddress": "example2#example.com"
},
"role": "REVIEWER"
}
]
}
'''
def obj = new JsonSlurper().parseText(json)
println obj.reviewers.collect{ it.user.name } // v1
println obj.reviewers*.user.name // the same as above but shorter
Using Java with library org.json.JSONObject;
JSONObject json =new JSONObject(YOUR_JSON_HERE );
JSONArray array = json.getJSONArray("reviewers" );
for(int i=0;i<array.length();i++){
JSONObject user =array.getJSONObject(i);
System.out.println(user.getJSONObject("user").get("name"));
}
}
You can get a list of names like this, using just Groovy:
jason = '''{
"reviewers": [
{
"user": {
"name": "name1.n1",
"emailAddress": "example#example.com"
},
"role": "REVIEWER"
},
{
"user": {
"name": "name2.n2",
"emailAddress": "example2#example.com"
},
"role": "REVIEWER"
}
]
}
'''
import groovy.json.JsonSlurper
def jsonslurper = new JsonSlurper()
def object = jsonslurper.parseText(jason)
List names = object.findAll { it.value instanceof List }
.values()
.flatten()
.collect { it.user.name }
println names

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 ignore the underlying structure of a JSON property and store it as a string?

I have a JSON file like this:
{
"Resources": {
"HelloWorldFunction": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler",
"Runtime": "nodejs8.10",
"Events": {
"HelloWorldApi": {
"Type": "Api",
"Properties": {
"Path": "/",
"Method": "GET"
}
}
},
"Policies": [
{
"SNSPublishMessagePolicy": {
"TopicName": {
"Fn::GetAtt": [
"HelloWorldTopic",
"TopicName"
]
}
}
}
],
"Environment": {
"Variables": {
"SNS_TOPIC_ARN": {
"Ref": "HelloWorldTopic"
}
}
},
"CodeUri": "nothing"
}
},
"HelloWorldTopic": {
"Type": "AWS::SNS::Topic",
"Properties": {
"Subscription": [
{
"Endpoint": "nothing",
"Protocol": "email"
}
]
}
}
}
}
I am using the Jackson YAMLFactory to parse a YAML-file that is equivalent to this JSON. How can I parse this in a way that all the content inside "Resources" is stored in a single String? (I want to keep this as a separate YAML/JSON for further analysis)
ObjectMapper mapper = new ObjectMapper();
String resources = mapper.readTree(new FileReader(path_to_your_json_file).at("/Resources").asText()
Or something like this.

Validate json schema of a particular JSON object from a response

I have a json response like this(Response is getting in the com.jayway.restassured.response.Response format).
[{
gameIdGlobal: 1947634,
season: 2017,
views: [{
name: "Recap",
displayOrder: 1,
groups: [{
type: "static",
displayOrder: 1
}
],
localizedName: {
ENG: "Recap",
ESP: "Resumen"
}
}
]
}
]
From this I need to validate the json schema of views object only.No need to validate the entire json . for that
I have created a json schema for views object only schema1.
schema1.json
{
"type": "array",
"items": {
"id": "view.json",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"displayOrder": {
"type": "integer",
"minimum": 1
},
"groups": {
"type": "array"
},
"localizedName": {
"type": "object",
"properties": {
"ENG": {
"type": "string",
"description": "the name of the view in english"
},
"ESP": {
"type": "string",
"description": "the name of the view in spanish"
}
}
}
}
}
}
How can i perform the schema validation of particular json object(views object from josn response)
code
Response response = RestAssured.given().when().get(getURL);
ValidatableResponse valResponse = response.then().contentType(ContentType.JSON);
valResponse.body(schema1.json("schema1.json")).assertThat();
You can specify that Additional Properties are allowed on the object that holds the array as its property. Here is the schema for the entire response json object:
{
"$schema": "http://json-schema.org/draft-06/schema#",
"type": "array",
"items": {
"type": "object",
"required": ["views"],
"additionalProperties": true,
"properties": {
"views": {
"type": "array",
"items": {
"id": "view.json",
...
}
}
}

Java extract information from JSON

I have the following JSON object:
{
"_class": "hudson.model.FreeStyleBuild",
"actions": [
{
"_class": "hudson.model.CauseAction",
"causes": [
{
"_class": "hudson.model.Cause$UserIdCause",
"shortDescription": "Started by user SYSTEM",
"userId": "SYSTEM",
"userName": "SYSTEM"
},
{
"_class": "hudson.model.Cause$UserIdCause",
"shortDescription": "Started by user SYSTEM",
"userId": "SYSTEM",
"userName": "SYSTEM"
},
{
"_class": "hudson.model.Cause$UserIdCause",
"shortDescription": "Started by user SYSTEM",
"userId": "SYSTEM",
"userName": "SYSTEM"
},
{
"_class": "com.sonyericsson.rebuild.RebuildCause",
"shortDescription": "Rebuilds build #1",
"upstreamBuild": 1,
"upstreamProject": "gcimpoies-test5",
"upstreamUrl": "job/gcimpoies-test5/"
},
{
"_class": "com.sonyericsson.rebuild.RebuildCause",
"shortDescription": "Rebuilds build #1",
"upstreamBuild": 1,
"upstreamProject": "gcimpoies-test5",
"upstreamUrl": "job/gcimpoies-test5/"
}
]
},
{
"_class": "hudson.model.CauseAction",
"causes": [
{
"_class": "com.sonyericsson.rebuild.RebuildCause",
"shortDescription": "Rebuilds build #1",
"upstreamBuild": 1,
"upstreamProject": "gcimpoies-test5",
"upstreamUrl": "job/gcimpoies-test5/"
}
]
},
{
},
{
"_class": "com.sonyericsson.jenkins.plugins.bfa.model.FailureCauseBuildAction"
},
{
},
{
},
{
}
],
"artifacts": [
],
"building": false,
"description": null,
"displayName": "#2",
"duration": 15,
"estimatedDuration": 61,
"executor": null,
"fullDisplayName": "gcimpoies-test5 #2",
"id": "2",
"keepLog": false,
"number": 2,
"queueId": 6,
"result": "FAILURE",
"timestamp": 1522153325922,
"url": "http://localhost:8080/job/gcimpoies-test5/2/",
"builtOn": "",
"changeSet": {
"_class": "hudson.scm.EmptyChangeLogSet",
"items": [
],
"kind": null
},
"culprits": [
]
}
And I want to extract the username: SYSTEM
I tried using JsonSlurper but with no luck. I believe the right way to go is using JSONObject instead.
Any help is much appreciated.
You can use Google Gson for parsing json in java. Here I am pasting the code to convert json into Map. So that you can simply access json as map object.
Map map = gson.fromJson(jsonString, Map.class);
System.out.println(map);
For more info, please read this thread.
Gson gson = new Gson();
Map buildDetailsMap;
buildDetailsMap = gson.fromJson(json, Map.class);
if (buildDetailsMap != null) {
List actions = (List) buildDetailsMap.get("actions");
Map actionZero = (Map) actions.get(0);
List causes = (List) actionZero.get("causes");
Map causeZero = (Map) causes.get(0);
username = (String) causeZero.get("userName");
}
This is how I did it. Thanks SV Madhava Revy

Categories

Resources