Get object from json array - java

May I know how to get JSON object from a json array??
JSON:
[
{
"id": 1,
"region": "Ilocos Region (Region I)",
"province": "Ilocos Norte",
"city": "Laoag City"
},
{
"id": 2,
"region": "Ilocos Region (Region I)",
"province": "Ilocos Norte",
"city": "Batac City"
},
{
"id": 3,
"region": "Ilocos Region (Region I)",
"province": "Ilocos Sur",
"city": "Vigan City"
}
]
I can get the region, province and city but I can't get the id.
Here is the code I'm using:
try {
br = new BufferedReader(new FileReader(path+"json/src_city.json"));
try {
while ((inputline = br.readLine()) != null) {
JSONArray a = (JSONArray) parser.parse(inputline);
for (Object o : a) {
JSONObject sample = (JSONObject) o;
id = (int) sample.get("id");
}}

if you can get the region, may be the reason is the id is int,you can not get by the way like this: id = (int) sample.get("id");

I think Jason uses only string values, try surrounding the number in quotes:
{
"id": "1",
"region": "Ilocos Region (Region I)",
"province": "Ilocos Norte",
"city": "Laoag City"
},
then you can parse it back to integer after retrieving it out of the object
id = Integer.valueOf(sample.get("id"));

We can get each jsonnode from the json array as shown below. And jsonnode provides method to parse the integer also.
if (a.isArray()) {
for (final JsonNode objNode : a) {
id = objNode.get("id").asInt();
}
}

Related

What is the best way to extract data from this JSON string? [duplicate]

I have some trouble with parsing a JSON response. The response data:
{
"deal": {
"categorie": {
"description": "Offres Shopping",
"idcategorie": "1",
"nom": "Shopping"
},
"conditions": "2 personne au plus",
"dateAjout": "2013-01-07T00:00:00+01:00",
"dateExp": "2013-01-31T00:00:00+01:00",
"description": "nuit dans un hotel 5 etoile",
"heurexp": "12",
"iddeal": "1",
"minutesexp": "30",
"prestataire": {
"adresse": "Qu zohour 44",
"codePostale": "12600",
"description": "Hotel 5 etoiles",
"idprestataire": "1",
"nom": "Hotel ronald",
"pays": "France",
"telephone": "99999999",
"ville": "Brest"
},
"prix": "80.0",
"prixHabituel": "200.0",
"tags": "hotel",
"titre": "Nuit 5 etoiles"
}
}
When trying to parse this response to a List<Deal> I get this exception:
com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArray
This is the code that I am using for the parse:
if (reponse != null && !reponse.isEmpty()) {
System.out.println(reponse);
Gson g = new Gson();
JsonParser parser = new JsonParser();
JsonObject jObject = parser.parse(reponse).getAsJsonObject();
JsonArray jArray = jObject.getAsJsonArray("deal"); // here goes the Exception
for (JsonElement elem : dealArray) {
deals.add(g.fromJson(elem, Deal.class));
}
System.out.println(deals.toString());
return "success";
}
thanks
Well, deal is not a JSON array, its a JSON object. Hence the exception. A JSON array, for reference, would look more like this:
"deal" : [{"attr" : "value"}, {"attr" : "value"}]

How to read JSON file in Java with simple json?

If I have a JSON like this:
{
"name": "Johnny",
"Gender": {
"male": true,
"female": false
},
"What does Johnny likes?": ["Travels", "Woman"],
"Travels": [
{
"Country": "Spain",
"City": "Madrid"
},
{
"Country": "Greece",
"City": "Kalokairi"
}
]
}
I know that I can do this to access to name:
object.getString("name");
To access gender I can do this:
JSONObject gender = (JSONObject) object.get("Gender");
gender.get("male");
gender.get("female");
To access What does Johnny likes? I can:
JSONArray likes = (JSONArray) objet.get("What does Johnny likes?");
Iterator<String> iterator = likes.iterator();
while (iterator.hasNext()) {
//code here
}
But how do I access Travels? I'm really not sure to understand it?
did you, try this?
JSONArray travels = (JSONArray) objet.get("Travels");
for(int j=0;j<travels.length();j++){
JSONObject travel = travels.getJSONObject(j);
}

Join two jsons based on element

I have two json files. I need to parse and join the json into a single structure
lineage.json
{
"lineage": [{
"sourceColumnId": "VMB_BESTADDRESS.SNAPSHOT_TS",
"description": "",
"targetColumnId": "VMB_BESTADDRESSUSAGE.NXREINS"
},
{
"sourceColumnId": "DSL_RECORD_SOURCES.MAMACT",
"description": "",
"targetColumnId": "G2_ZUMADF00.MAMACT"
},
{
"sourceColumnId": "DSL_RECORD_SOURCES.MAMADE",
"description": "",
"targetColumnId": "G2_ZUMADF00.HDF_S_POL_GEN"
}]
}
column.json
{
"column": [{
"ID": 39700,
"columnId": "VMB_BESTADDRESS.SNAPSHOT_TS",
"column": "SNAPSHOT_TS",
"dataType": "String",
"length": "",
"table": "VMB_BESTADDRESS",
},
{
"ID": 39701,
"columnId": "VMB_BESTADDRESSUSAGE.NXREINS",
"column": "NXREINS",
"dataType": "String",
"length": "",
"table": "VMB_BESTADDRESSUSAGE",
},
{
"ID": 39702,
"columnId": "VMB_BESTADDRESSUSAGE.PKADDRESSCODE",
"column": "PKADDRESSCODE",
"dataType": "String",
"length": "",
"table": "VMB_BESTADDRESSUSAGE",
}]
}
I need to join the two jsons such that for every match of sourcecolumnId and targetcolumnid in column the following json structure must be populated
{
output:{
sourceColumnId:VMB_BESTADDRESS.SNAPSHOT_TS,
sourceColumnName:SNAPSHOT_TS,
targetColumnId:VMB_BESTADDRESSUSAGE.NXREINS,
targetColumnNameNXREINS,
}
}
I need to join lookup two json to get the output such that
sourceColumnName -> column name from column.json whose columnId and sourceColumnId are same.
similarly for targetcolumnName also.
String str = "xxx"; // column.json
JSONArray jsonArrayColumn = JSON.parseObject(str);
Map<String, JSONObject> column = new HashMap(); // {id:name}
for(int i = 0; i < jsonArrayColumn.size(); i++){ // loop
JSONObject obj = jsonArrayColumn.getJSONObject(i);
column.put(obj.getString("columnId"), obj.getString("column"));
}
String str2 = "xxx"; // lineage.json
JSONArray jsonArrayLineage = JSON.parseObject(str2);
JSONArray resultArray = new JSONArray();
for(int i = 0; i < jsonArrayLineage.size(); i++){ // loop
JSONObject lineageObj = jsonArrayLineage.getJSONObject(i);
JSONObject obj = new JSONObject();
obj.put("sourceColumnId", lineageObj.get("sourceColumnId"));
obj.put("sourceColumnName", column.get(lineageObj.get("sourceColumnId")));
obj.put("targetColumnId", lineageObj.get("targetColumnId"));
obj.put("targetColumnName", column.get(lineageObj.get("targetColumnId")));
}
The resultArray is what you want.

Can't access variable in JSON

I'm having trouble with my JSONObject
this is my code :
importPackage(Packages.org.apache.commons.io);
importPackage(Packages.java.io);
fisTargetFile = new FileInputStream(new File("C:/moe.json"));
input = IOUtils.toString(fisTargetFile, "UTF-8");
jsonData = input;
myJSONObject = eval('(' + jsonData + ' )');
len = myJSONObject.cells.length;
count = 0;
if (count < len) {
var name = myJSONObject.cells[count].attrs.text;
var type = myJSONObject.cells[count].type;
var photo = myJSONObject.cells[count].attrs.image.xlink:href;
row["name"] = name;
row["type"] = type;
// row["photo"] = photo;
count++;
return true;
}
return false;
My problem is in this line var photo = myJSONObject.cells[count].attrs.image.xlink:href;
i can't access my Image data because this is not a correct syntax ":" how can i overcome it ? is there a way to escape the ":" ?
Edit :
this is my JSON object :
{
"cells": [
{
"type": "basic.Platform",
"size": {
"width": 60,
"height": 60
},
"custom": {
"identifier": [
{
"name": "Name1",
"URI": "Value1"
}
],
"classifier": [
{
"name": "Name2",
"URI": "Value2"
}
],
"output": [
{
"name": "Name3",
"URI": "Value3"
}
],
"imported": false,
"event": [
]
},
"ref": [
],
"uuid": [
"dc537ba7-b9dc-476e-9f09-8c1f5211f9bb"
],
"position": {
"x": 390,
"y": 230
},
"angle": 0,
"id": "dc537ba7-b9dc-476e-9f09-8c1f5211f9bb",
"embeds": "",
"z": 1,
"description": "",
"attrs": {
"text": {
"font-size": "9",
"text": "rere",
"ref-x": "0.5",
"ref-dy": "20",
"fill": "#000000",
"font-family": "Arial",
"display": "",
"stroke": "#000000",
"stroke-width": "0",
"font-weight": "400"
},
"image": {
"width": 50,
"height": 50,
"xlink:href": "data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAG4AAACWCAYAAAA\/mr2PAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS5EOsBjwfqm3fvx0eIfsT89"
}
}
}
]
}
I have trimmed the xlink:href data because it's too long.
Yes there is
myJSONObject.cells[count].attrs.image["xlink:href"]
Reasoning: Any where you use the dot notation to separate object references you can also use the square bracket notation and pass in a string. This is the standard way to reference something that is not a "valid" identifier such as a colon in the middle of a name.
In JavaScript, objects are also associative arrays (or hashes).
That is, the property foo.bar can also be read or written by calling foo["bar"]
var photo = myJSONObject.cells[count].attrs.image["xlink:href"];
You may try to access it like a property of image["xlink:href"].
Or please specify what that column stands for.

JSONObject to String returns null (with valid JSON)

I am facing the following difficulty:
I create a JSONObject.
With System.out.println (finalJson) I get the output below. It is valid JSON according to JSONLint. But when I try to get the String representationn by calling finalJson.toString (), it only returns null. How is that possible? What am I missing here?
{
"id": "cell: chris-VirtualBoxCell01",
"name": "cell: chris-VirtualBoxCell01",
"data": {},
"children": [
{
"id": "node: chris-VirtualBoxNode01",
"name": "node: chris-VirtualBoxNode01",
"data": {},
"children": [
{
"id": "applicationServer: C4Cluster_server1",
"name": "applicationServer: C4Cluster_server1",
"data": {},
"children": []
},
{
"id": "nodeAgent: nodeAgent",
"name": "nodeAgent: nodeAgent",
"data": {},
"children": []
}
]
},
{
"id": "deploymentManagerNode: chris-VirtualBoxCellManager01",
"name": "deploymentManagerNode: chris-VirtualBoxCellManager01",
"data": {},
"children": [
{
"id": "deploymentManager: deploymentManager",
"name": "deploymentManager: deploymentManager",
"data": {},
"children": []
}
]
}
]
}
Here's the snippet that should be of interest:
//Get JSON from Grails domain model
JSON json = ServerNode.findAll ("from ServerNode as s where s.root=true") as JSON;
//check result
System.out.println (json);
//turn into a JSONObject by chopping off surrounding []
String jsonString = json.toString ().substring (1, json.toString ().length ()-1);
//check result
System.out.println (jsonString);
//render to JSONObject
JSONObject jObject = new JSONObject (jsonString);
//modify structure a little more
JSONObject finalJson = modifyJson (jObject);
//check the final form (produces the above output)
System.out.println (finalJson);
//turn into string and print --> returns null
String jString = finalJson.toString ();
System.out.println (jString);

Categories

Resources