How to create a JSON structure for this - json

Can you tell me how to create a Json objecct for this
I think it is a JSON with children JSON objects.
[{
"data": {
"ID": "56e819a90111257894be41c9e310f8cb",
"name": "Email_____2016-03-15 10_18_16",
"objCode": "DOCU",
"description": null,
"lastUpdateDate": "2016-03-15T10:18:17:551-0400"
}
}: null]
I did this
JSONObject childVal = new JSONObject();
JSONObject parent = new JSONObject();
try {
childVal.put("ID", "56e819a90111257894be41c9e310f8cb");
childVal.put("name", "Email_____2016-03-15 10_18_16");
childVal.put("objCode", "DOCU");
childVal.put("description", "null");
childVal.put("lastUpdateDate", "2016-03-15T10:18:17:551-0400");
parent.put("data", childVal);
but how do i get the parent [ object : null]
thanks

Related

how can I exclude a key value pair if jsonArray is sending empty array?

jsonArray.put(jsonObject);
if (!jsonArray.isEmpty()) {
shopProductJsonObject.put("productBasedOffer", jsonArray);
shopProductListJsonArray.put(shopProductJsonObject);
}
"productBasedOffer": [
{
"offerKeyword": "null",
"minAmount": "0.0",
"offerType": "PRODUCT_BASED",
"amount": "50.0",
"offerId": "27",
"freeProductId": "0",
"endTime": "1613757599000",
"offerCategory": "FIXED"
}
]
"productBasedOffer": []
If jsonArray is sending empty array, I want to skip that key value pair.
how can I implement this? I'm using spring boot.
Get the JSONArray :
JSONObject jsonObject = new JSONObject(yourString); // yourString is String type
JSONArray arr = jsonObject.getJSONArray("productBasedOffer");
if(arr!=null && arr.length()>0)
{
//Do something
}
If you write your logic in if() block, then of course it'll skip the current one.

parsing json object with number as its key fields?

I'm trying to parse json into kotlin objects but the problem is that its key fields are numbers any idea how can parse them , I've tried serialized name but still facing problem.
The json response looks like this :
{
"Id": [{
"1": {
"name": "name1",
"class": "11a"
}
},
{
"2": {
"name": "name2",
"class": "11b"
}
}
]
}
I'm using gson and the main thing i'm trying to do is to store this number fields as some other string objects.
You can parse them into a list of maps, then "map" those to your data classes instead:
val input = """{
"Id": [{
"1": {
"name": "name1",
"class": "11a"
}
},
{
"2": {
"name": "name2",
"class": "11b"
}
}
]
}"""
val gson = Gson()
val parsed: Map<String, List<Map<String, Any>>> =
gson.fromJson(input, (object : TypeToken<Map<String, List<Map<String, Any>>>>(){}).type)
println(parsed["Id"]?.get(0)?.get("1")) // {name=name1, class=11a}
It will have some nasty generic signature, though.
If you're working with Kotlin, take a look at Klaxon, it will improve your experience.

Unexpected character (g) at position 0 when trying to parse json - HttpResponseDecorator

Whenever I try to execute below script I keep getting error, saying unexpected character (g).
Basically I want to be able to parse the json response and be able to get the upstream job name from it.
Script:
#Grapes([
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1'),
#Grab(group='commons-collections', module='commons-collections', version='3.2.1'),
#Grab(group='org.jsoup', module='jsoup', version='1.10.2'),
#Grab(group='org.json', module='json', version='20190722'),
#Grab(group='com.googlecode.json-simple', module='json-simple', version='1.1.1')
])
import static groovyx.net.http.ContentType.*
import groovyx.net.http.HttpResponseException
import groovyx.net.http.RESTClient
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
import java.net.*
import java.util.*
import org.json.simple.*
import org.json.simple.parser.JSONParser;
def getRestClient(){
String jenkinsUrl="http://somedomainname:8080"
def restClient = new RESTClient(jenkinsUrl)
return restClient
}
def getJobsInfo(String jobname,RESTClient restClient){
def requrl= '/job/'+jobname+'/lastBuild/api/json/?pretty=true'
def response = restClient.get( path : requrl)
return response
}
def writeToPropertyFile(){
def jsonResponseObject = getJobsInfo("sampleJobName",getRestClient())
println "\n\n\n\n\n Json String :---- "+ jsonResponseObject.toString()
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonResponseObject.toString());
JSONArray upstreamJobInfoArray = jsonObject.getJSONArray("causes");
for (int i = 0; i < upstreamJobInfoArray.length(); i++) {
JSONObject jobCauses = upstreamJobInfoArray.getJSONObject(i);
String upstreamProjectName = jobCauses.getString("upstreamProject");
println upstreamProjectName
}
}
writeToPropertyFile()
Error :
Json String :---- groovyx.net.http.HttpResponseDecorator#6b063470
Caught: Unexpected character (g) at position 0.
Unexpected character (g) at position 0.
at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at org.json.simple.parser.JSONParser$parse.call(Unknown Source)
at getUpstreamJob.writeToPropertyFile(getUpstreamJob.groovy:39)
at getUpstreamJob.run(getUpstreamJob.groovy:50)
EDIT 1 : START
JSON response that I am trying to parse :
{
"_class": "hudson.model.FreeStyleBuild",
"actions": [
{
"_class": "hudson.model.CauseAction",
"causes": [
{
"_class": "hudson.model.Cause$UpstreamCause",
"shortDescription": "Started by upstream project \"sampleJobName\" build number 712",
"upstreamBuild": 712,
"upstreamProject": "sampleJobName",
"upstreamUrl": "job/sampleJobName/"
},
{
"_class": "hudson.model.Cause$UserIdCause",
"shortDescription": "Started by user Malick, Asif",
"userId": "asifma00",
"userName": "Malick, Asif"
},
{
"_class": "com.sonyericsson.rebuild.RebuildCause",
"shortDescription": "Rebuilds build #300",
"upstreamBuild": 300,
"upstreamProject": "sampleJobName",
"upstreamUrl": "view/ABCProjectView/job/sampleJobName/"
}
]
},
{
"_class": "hudson.model.ParametersAction",
"parameters": [
{
"_class": "hudson.model.StringParameterValue",
"name": "SNAPSHOTNAME",
"value": "ABCDE_12121.2000-2121212121212"
},
{
"_class": "hudson.model.StringParameterValue",
"name": "BUILD_LABEL",
"value": "ABCDE_12121.2000"
}
]
},
{},
{},
{},
{},
{
"_class": "hudson.plugins.parameterizedtrigger.BuildInfoExporterAction"
},
{},
{},
{},
{}
],
"artifacts": [],
"building": false,
"description": null,
"displayName": "#301",
"duration": 1199238,
"estimatedDuration": 1194905,
"executor": null,
"fullDisplayName": "sampleJobName #301",
"id": "301",
"keepLog": false,
"number": 301,
"queueId": 189076,
"result": "SUCCESS",
"timestamp": 1583500786857,
"url": "http://somedomainname:8080/job/sampleJobName/301/",
"builtOn": "Server12345",
"changeSet": {
"_class": "hudson.scm.EmptyChangeLogSet",
"items": [],
"kind": null
},
"culprits": []
}
EDIT 1 : END
I have tried looking at several Stack Overflow issues, but still haven't been able to resolve it.
Please guide.
It's because you're not getting the actual JSON string, you're getting the toString() output on a groovyx.net.http.HttpResponseDecorator class.
You can see it printing it out here (it's easy to miss though... I missed it the first look 🙂):
Json String :---- groovyx.net.http.HttpResponseDecorator#6b063470
I think you need to call jsonResponseObject.data to get the parsed data, and it might even return you a Map parsed form the JSON (so you can get rid of all your JSONObject code). Test it by changing to:
def data = jsonResponseObject.data
println "\n\n\n\n\n Json ${data.getClass().name} :---- $data" jsonResponseObject.toString()
If it is a java.util.Map, you can simplify your second part from:
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonResponseObject.toString());
JSONArray upstreamJobInfoArray = jsonObject.getJSONArray("causes");
for (int i = 0; i < upstreamJobInfoArray.length(); i++) {
JSONObject jobCauses = upstreamJobInfoArray.getJSONObject(i);
String upstreamProjectName = jobCauses.getString("upstreamProject");
println upstreamProjectName
}
To (using data from above):
data.actions.causes.upstreamProject.flatten().each { println it }

How to Get JSON Object Within JSON Array

i want to get avatar_url in actor object. i can get "id" and "type" to show in recyclerview. but avatar_url not show image why?
json url
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for(int i=0; i<response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Article article = new Article();
article.setAvatar_url(jsonObject.getString("avatar_url"));
article.setId(jsonObject.getString("id"));
article.setType(jsonObject.getString("type"));
articles.add(article);
how i get avatar_url from actor field?
and yes i can run because i delete
article.setAvatar_url(jsonObject.getString("avatar_url"));
Thanks
Looking at your JSON, you can see that the "avatar_url" isn't a peer of the "id" and "type".
"id": "11392115556",
"type": "PushEvent",
"actor": {
"id": 8517910,
"login": "LombiqBot",
"display_login": "LombiqBot",
"gravatar_id": "",
"url": "https://api.github.com/users/LombiqBot",
"avatar_url": "https://avatars.githubusercontent.com/u/8517910?"
},
You need to retrieve the "actor" object and then get the "avatar_url" from within that object.

GSON deserialize as array although JSON source is object

I'd like to deserialize this using GSON into a list of Post, but can't figure out how to tell GSON how to ignore the root element "posts" (as its an object) and just process the array.
I've got:
Type postTypeList = new TypeToken<List<Post>>(){}.getType();
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(myJSONString);
JsonObject postsRootObj = jsonElement.getAsJsonObject();
List<Post> postList = gson.fromJson(postsRootObj.get("posts"), postTypeList);
BUT.. I'd rather not have the whole JsonParser, I'd rather just pass it directly into the gson.fromJson function.. Is there a way to do this?
{ "posts":
[
{
"username": "John",
"message": "I'm back",
"time": "2010-5-6 7:00:34"
"validator":[{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
}]
}
,
{
"username": "Smith",
"message": "I've been waiting",
"time": "2010-4-6 10:30:26"
"validator":[{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
}]
}
]}
Create a wrapper class which will have List<Post> as its member
public class PostList{
private List<Post> posts;
// getter and setters for posts
}
And then use fromJson in the similar fashion
List<Post> postList = gson.fromJson(myJSONString,PostList.class);
There is a correction from above. Usage should be :
PostList postList = gson.fromJson(myJSONString,PostList.class);
Post post = postlist.get(index) //index is the index of list you want to access