This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
I have a JSON string as below which I am obtaining from a web service call. How can I retrieve the array from the builds key.
{
"actions" : [
{
},
null,
{
}
],
"description" : "Download Branch Build",
"displayName" : "EPIC-AUTODEV-8413",
"displayNameOrNull" : null,
"name" : "EPIC-AUTODEV-8413",
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/",
"buildable" : false,
"builds" : [
{
"number" : 71,
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/71/"
},
{
"number" : 70,
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/70/"
},
{
"number" : 69,
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/69/"
},
{
"number" : 68,
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/68/"
},
{
"number" : 67,
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/67/"
},
{
"number" : 66,
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/66/"
},
}
I tried with tree=builds[*], but it gives me output like this
{"builds":[{},{},{},{},{},{},{},{},{},{},{}]}
try out javascript method JSON.parse, below is example
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
the above will give you object and than you refer part you want.
and if you want your object convert back in to json than try JSON.stringify()
var myJSON = JSON.stringify(obj);
Related
I have an String called inputJson that contains
{"listPruebas": [
{
"nombrePrueba" : "pruebaA",
"id" : 1,
"tipoPrueba" : "PRUEBABASE1",
"elementoBase" : "tipoA",
"listaMarca": [
{
"elemento": "elemento1 ",
"tipo": "ABC",
"cadena": "SFSG34235WF32"
},
{
"elemento":"elemento2",
"tipo":"DEF",
"cadena":"DJRT64353GSDG"
},
{
"elemento" : "elemento3",
"formato ":"JPG"
}
]},
{
"nombrePrueba" : "pruebaB",
"id" : 2,
"tipoPrueba" : "PRUEBABASE2",
"elementoBase" : "imagenPrueba",
"listaMarca2": [
{
"elemento" : "imagen",
"tipo": "tipo5",
"cadena": "iVBORw0KGgoAAAANSUhEUgAAAgAAAA"
}
]
}
],
"listaBuscar":
[
{
"tipoBusqueda":"busqueda1",
"id" : 1,
"operacion" : "operacion1",
"valor" : "12"
},
{
"tipoBusqueda":"binario",
"id" : 2,
"operacion" : "operacion2",
"valor" : "13"
},
{
"tipoFiltro":"numerico",
"id" : 31,
"operacion" : "MENOR_QUE",
"valor" : "1980",
"intervalo" : 1
}
]
}
and I converted the String to JSONObject of this way
JSONObject object = new JSONObject(inputJson);
and I got this
jsonObject::{"listaBuscar":[{"valor":"12","id":1,"operacion":"operacion1","tipoBusqueda":"busqueda1"},{"valor":"13","id":2,"operacion":"operacion2","tipoBusqueda":"binario"},{"tipoFiltro":"numerico","intervalo":1,"valor":"1980","id":31,"operacion":"MENOR_QUE"}],"listPruebas":[{"listaMarca":[{"tipo":"ABC","elemento":"elemento1","cadena":"SFSG34235WF32"},{"tipo":"DEF","elemento":"elemento2","cadena":"DJRT64353GSDG"},{"elemento":"elemento3","formato":"JPG"}],"elementoBase":"tipoA","tipoPrueba":"PRUEBABASE1","nombrePrueba":"pruebaA","id":1},{"elementoBase":"imagenPrueba","tipoPrueba":"PRUEBABASE2","listaMarca2":[{"tipo":"tipo5","elemento":"imagen","cadena":"iVBORw0KGgoAAAANSUhEUgAAAgAAAA"}],"nombrePrueba":"pruebaB","id":2}]}
and now I need to extract information but I dont know how to do, for example I try this
object.getString("elemento1");
but I got this error
Caused by: org.json.JONException: JSONObject["elemento1"] not found
help me please
You can't get a nest JSON object from the top level. It's like a treemap. You need to convert it into a java object or get it level by level.
check this post, a lot of ways.
You json contains two json arrays, fetch them as -
JSONArray listaBuscArray = jsonObj.getJSONArray("listaBuscar");
JSONArray listPruebasArray = jsonObj.getJSONArray("listPruebas");
Now you can process and use them as -
for(int i=0; i<listaBuscArray.length; i++){
JSONObject obj = listaBuscArray.getJSONObject(i);
.... your logic
}
Hi I'm reading data from mongodb into spark application.
My mongodb contains 2 collections.
One is profile_data(actual data with field names)
(Which holds all the input data including some unique fields)
{
"MessageStatus" : 2,
"Origin" : 1,
"_id" : ObjectId("596340fe8b0fa35d2880db1a"),
"accerlation" : 19.4,
"cylinders" : 4,
"displacement" : 119,
"file_id" : ObjectId("59633e48b760e7c8071a6c1c"),
"horsepower" : 82,
"modelyear" : 82,
"modified_date" : ISODate("2017-07-10T08:47:01.641Z"),
"mpg" : 31,
"snet_id" : "new_project",
"unique_id" : "784",
"username" : "chevy s-10",
"weight" : 2720
}
And another collection is : predictive_model_details(Which holds the ML model details like model name, feature fields and prediction field just like metadata)
{
"_id" : ObjectId("56b4351be4b064bb19a90324"),
"algorithm_id" : "55d717a53d9e22022ff2a1e9",
"algorithm_name" : "K- Nearest Neighbours (IBK)",
"client_id" : "562e1d51b760d0e408151b91",
"feature_fields" : [
{
"name" : "Origin",
"type" : "int"
},
{
"name" : "accerlation",
"type" : "Double"
},
{
"name" : "displacement",
"type" : "Int"
},
{
"name" : "horsepower",
"type" : "Int"
},
{
"name" : "modelyear",
"type" : "Int"
}
],
,
"makeActiveStatus" : "0",
"model_name" : "test1",
"parameter_type" : "system_defined",
"parameters" : [
{
"symbol" : "-K",
"value" : "1"
}
],
"predictor" : {
"name" : "mpg"
"type" : "Int"
},
"result_exists" : true,
"snet_id" : "new_project"
}
So I've created 2 datasets in spark for two collections in MongoDB. Now I want to map these 2 Datasets with all feature fields together and prediction field together.
And common field in 2 datasets is snet_id.
Could anyone please help?
Ok so I am making API requests to retrieve certain things like movies, songs, or to ping the server. However all of these responses are contained within the same response JSON object that has varying fields depending on the response. Below are three examples.
ping
{
"response" : {
"status" : "ok",
"version" : "0.9.1"
}
}
getIndexes
{
"response" : {
"status" : "ok",
"version" : "0.9.1",
"indexes" : {
"index" : [ {
"name" : "A",
"movie" : [ {
"id" : "150",
"name" : "A Movie"
}, {
"id" : "2400",
"name" : "Another Movie"
} ]
}, {
"name" : "S",
"movie" : [ {
"id" : "439",
"name" : "Some Movie"
}, {
"id" : "209",
"name" : "Some Movie Part 2"
} ]
} ]
}
}
}
getRandomSongs
{
"response" : {
"status" : "ok"
"version" : "0.9.1"
"randomSongs" : {
"song": [ {
"id" : "72",
"parent" : "58",
"isDir" : false,
"title" : "Letter From Yokosuka",
"album" : "Metaphorical Music",
"artist" : "Nujabes",
"track" : 7,
"year" : 2003,
"genre" : "Hip-Hop",
"coverArt" : "58",
"size" : 20407325,
"contentType" : "audio/flac",
"suffix" : "flac",
"transcodedContentType" : "audio/mpeg",
"transcodedSuffix" : "mp3",
"duration" : 190,
"bitRate" : 858,
"path" : "Nujabes/Metaphorical Music/07 - Letter From Yokosuka.flac",
"isVideo" : false,
"created" : "2015-06-06T01:18:05.000Z",
"albumId" : "2",
"artistId" : "0",
"type" : "music"
}, {
"id" : "3135",
"parent" : "3109",
"isDir" : false,
"title" : "Forty One Mosquitoes Flying In Formation",
"album" : "Tame Impala",
"artist" : "Tame Impala",
"track" : 4,
"year" : 2008,
"genre" : "Rock",
"coverArt" : "3109",
"size" : 10359844,
"contentType" : "audio/mpeg",
"suffix" : "mp3",
"duration" : 258,
"bitRate" : 320,
"path" : "Tame Impala/Tame Impala/04 - Forty One Mosquitoes Flying In Formation.mp3",
"isVideo" : false,
"created" : "2015-06-29T21:50:16.000Z",
"albumId" : "101",
"artistId" : "30",
"type" : "music"
} ]
}
}
}
So basically my question is, how should I structure my model classes to use for parsing these responses? At the moment I have an abstract response object that only contains fields for the status and version. However, by using this approach I will need a response class that extends this abstract class for ever request I make (e.g. AbstractResponse, IndexesResponse, RandomSongsResponse). Also, some models with the same name may have different fields depending on the API request made. I would prefer to avoid making a model class for every possible scenario.
And as an extra note, I am using GSON for JSON serialization/deserialization and Retrofit to communicate with the API.
I'm aware of the writerWithDefaultPrettyPrinter option in Jackson, but is there any way to customize it? See examples below.
If this isn't possible in Jackson, if you can't change pretty print options, then is there another popular JSON library that would do it?
Summary of options to change:
Don't open multiple containers on the same line
Don't close and open containers on the same line
Use 4 spaces as indents instead of 2
(another option, though I wouldn't use it) Open containers on a new line so that they line up vertically with their closing marker
Example of what it outputs now:
[ {
"id" : "12",
"payload" : [ {
"name" : "url",
"value" : [ {
"name" : "url",
"value" : "http://foobar.com"
} ]
}, {
"name" : "tags",
"value" : [ {
"name" : "tags",
"value" : "red"
}, {
"name" : "tags",
"value" : "green"
}, {
"name" : "tags",
"value" : "blue"
}, {
...
Example of what I'd like to get:
[
{
"id" : "12",
"payload" : [
{
"name" : "url",
"value" : [
{
"name" : "url",
"value" : "http://foobar.com"
}
]
},
{
"name" : "tags",
"value" : [
{
"name" : "tags",
"value" : "red"
},
{
"name" : "tags",
"value" : "green"
},
{
"name" : "tags",
"value" : "blue"
},
{
...
Using REST API, I am getting the JSON response from the below Ajax hit for loading datatable.
I am getting error: Uncaught TypeError: Cannot read property 'length' of undefined.
$('#example').dataTable({
"bSort" : false,
"bDestroy" : true,
"sPaginationType" : "full_numbers",
"bProcessing" : false,
"bFilter" : true,
"bServerSide" : true,
"bAutoWidth" : false,
"sAjaxSource" : 'exampledatagrid.json?token=' + sessionId,
"aoColumns" : [{
"mData" : "0",
"mData" : "1",
"mData" : "2",
"mData" : "3"
}],
"fnServerParams" : function(aoData) {
alert(aoData);
aoData.push({
"name" : "colNameMode",
"value" : "userStatusList"
}, {
"name" : "colName_0",
"value" : "userIDList"
}, {
"name" : "colName_1",
"value" : "userNameList"
}, {
"name" : "colName_2",
"value" : "userRemarksList"
});
},
"fnRowCallback" : function(nRow, aData, iDisplayIndex) {
alert(aData);
},
"fnDrawCallback" : function(oSettings) {
if ( oSettings.bSorted || oSettings.bFiltered ) {
for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ ) {
$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
}
}
}
});
JSON response is :
{"userRemarksList":["TECHNOLOGY","GUEST","HOUSE","SECURITY"],"userIDList":[23,45,23,54],"userNameList":["Michael","Danny","Rahil","Ramesh"],"userStatusList":[0,0,1,1]}
I want to know whether I have to change my JSON format or if I can retrieve from the above JSON response itself?
I got the answer by making a change in my back-end by quering the results using hibernate "org.hibernate.query". from this i was able to obtain the list of records (one-by-one) and load it into the grid respectively.