Join two jsons based on element - java

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.

Related

How to dynamically simplify json using java?

I have received a json string like so:
{
"data": [
{
"name": "Order",
"value": "2"
},
{
"name": "Address",
"value": "182"
},
{
"name": "DNS",
"value": "null"
},
{
"name": "SSID",
"value": "work"
},
{
"name": "Protocol",
"value": "0"
},
{
"name": "Key",
"value": ""
},
{
"name": "carrier",
"value": "undefined"
},
{
"name": "SSH",
"value": "1"
},
{
"name": "ntp_addr",
"value": ""
},
{
"name": "Name",
"value": ""
}
]
}
I used stringify on an html response and this is what I have to parse. As you can see, it is pretty redundant; I would much rather { "Order":"2" } than { "name":"Order","value":"2" } ... So an array of name-value pairs, instead of an array of objects.
Is there a way I can dynamically format this response so that it will be easier to parse?
What 'd like is to be able to say:
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject dataObject = data.getJSONObject(i);
String order = dataObject.getString("Order");
String address = dataObject.getString("Address");
// etc...
}
But the current format makes it almost impossible to parse. I'd need loops within loops.
I'd like to use com.google.gson library. And this response easy to parse with it:
private final JsonParser PARSER = new JsonParser();
public void parse(String jsonString) {
JsonObject dataObject = PARSER.parse(jsonString).getAsJsonObject();
JsonArray dataArray = dataObject.get("data").getAsJsonArray();
dataArray.iterator().forEachRemaining(element -> {
String name = element.getAsJsonObject().get("name").getAsString();
String value = element.getAsJsonObject().get("value").getAsString();
}
}
Or you can simply use TypeAdapters for json deserialization directly in the object.
Something like this should do the trick
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
JSONObject simplifiedDataObject = new JSONObject();
for (int i = 0; i < data.length(); i++) {
JSONObject dataField = data.getJSONObject(i);
simplifiedDataObject.put(dataField.getString("name"), dataField.get("value"));
}
You just iterate over each element in data, use the name field as the field on a new JSONObject and simply retrieve the value using the value key.

How to Create a JSONArray using JSONObject with all values from a database table in java

I am fetching details from a database table which contains 3 rows in JAVA.
I am using JSONarray and JSONObject as follows
JSONObject jsonObject = new JSONObject();
JSONObject mainjsonObject = new JSONObject();
JSONArray ja=new JSONArray();
The data from table is put to the jsonObject as follows for each one:
String qry="select * from details";
ResultSet res = select .executeQuery(qry);
while(res.next){
String Name=res.getString("name");
.
.
jsonObject.put("Name", Name);
.
.
ja.put(jsonObject);
}
mainjsonObject.put("PERSONAL DETAILS",ja);
i should get the output json as follows:
{
"PERSONAL DETAILS": [
{
" name": "abc",
"age": "4",
"gender": "F",
"Place": "abc1"
},
{
" name": "xyz",
"age": "3",
"gender": "M",
"Place": "abc2"
}
]
}
But am getting same values in both like below:
{
"PERSONAL DETAILS": [
{
" name": "abc",
"age": "4",
"gender": "F",
"Place": "abc1"
},
{
" name": "abc",
"age": "4",
"gender": "F",
"Place": "abc1"
}
]
}
Please help me with a solution. I need to get all the values from the tables as an array in JSON format
you need to create new JSONObject in your loop otherwise the last record will be shown everywhere
while(res.next()){
String Name=res.getString("name");
jsonObject = new JSONObject();
// ^^^^^^^^
jsonObject.put("Name", res.getString(1));
jsonObject.put("age", res.getString(2));
jsonObject.put("gender", res.getString(3));
jsonObject.put("Place", res.getString(4));
ja.put(jsonObject);
}
The problem is that you are reusing the same JSONObject over and over. And this is basically a Map.
What you need to do is create a new JSONObject instance and put it in the array for each iteration:
JSONObject obj;
while (rs.next()) {
obj = new JSONObject();
// fill in obj
ja.put(obj);
}

Get object from json array

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();
}
}

Write json strings using java (JSP)

I want to create a json string like below.
"data": [{
"id": "1",
"data": "one",
"color": "008ee4"
},{
"id": "2",
"data": "two",
"color": "008ee4"
}]
So far I have come up with this.
<%
JSONObject outerObject = new JSONObject();
JSONArray outerArray = new JSONArray();
JSONObject innerObject = new JSONObject();
JSONArray innerArray = new JSONArray();
innerObject.put("label", "1");
innerObject.put("value", "one");
innerObject.put("color", "008ee4");
outerObject.put("data", outerArray);
System.out.println(outerObject.toString());
%>
And it gives the output like
{"data":[]}
I want to remove those curly brackets and input data inside square brackets. Please help me.
UPDATE
{
type: "line",
renderAt: "chartContainer1",
width: "500",
height: "300",
dataFormat: "json",
"dataSource": {
"chart": {
"caption": "Total Revenues from 2008-2013",
"numberprefix": "$",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"plotbordercolor": "008ee4",
"plotborderthickness": "3",
"showvalues": "0",
"divlinecolor": "CCCCCC",
"showcanvasborder": "0",
"tooltipbgcolor": "00396d",
"tooltipcolor": "FFFFFF",
"tooltipbordercolor": "00396d",
"numdivlines": "2",
"yaxisvaluespadding": "20",
"anchorbgcolor": "008ee4",
"anchorborderthickness": "0",
"showshadow": "0",
"anchorradius": "4",
"chartrightmargin": "25",
"canvasborderalpha": "0",
"showborder": "0"
},
"data": [
{
"label": "2009",
"value": "4400000",
"color": "008ee4"
},
{
"label": "2010",
"value": "4800000",
"color": "008ee4"
},
{
"label": "2011",
"value": "5500000",
"color": "008ee4"
},
{
"label": "2012",
"value": "6700000",
"color": "008ee4",
"anchorradius": "7",
"tooltext": "Historical high"
},
{
"label": "2013",
"value": "4200000",
"color": "008ee4"
}
]
}
}
Above is the main json file. I just want to replace the data part with my data.
Do it like this:
JSONObject outerObject = new JSONObject();
JSONArray outerArray = new JSONArray();
JSONObject innerObject = new JSONObject();
JSONArray innerArray = new JSONArray();
innerObject = new JSONObject();
innerObject.put("label", "1");
innerObject.put("value", "one");
innerObject.put("color", "008ee4");
innerArray.add(innerObject);
outerObject.put("data", innerArray);
System.out.println(outerObject.toString());

Accessing json string in java and creating hashmap Android

I have a JSON string and I am trying to retrieve information from it. Json String looks like this.
JSON STRING :
{
"information": {
"device": {
"id": 0
},
"user": {
"id": 0
},
"data": [
{
"datum": {
"id": "00GF001",
"history_id": "9992BH",
"name": "abc",
"marks": 57,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "72BA9585",
"history_id": "78NAH2",
"name": "ndnmanet",
"marks": 70,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "69AHH85",
"history_id": "NN00E3006",
"name": "kit",
"department": "EF003",
"class": "A",
"type": "Employee"
}
},
{
"datum": {
"id": "09HL543",
"history_id": "34QWFTA",
"name": "jeff",
"department": "BH004",
"class": "A1",
"type": "Employee_HR"
}
}
]
}
}
I am trying to access data JSONArray and respective Datum from it. I differentiated each datum as per type such as student, employee etc and push information in hashmap.
I successfully did it in javascript but in Java I am struggle abit.
When I am trying to access JSONArray it throws exception
try {
JSONObject data = new JSONObject(dataInfo);
// Log.d(TAG, "CHECK"+data.toString());
JSONObject info = data.optJSONObject("information");
if(info.getJSONArray("data").getString(0).equals("Student") > 0) //exception here
Log.d(TAG, "Data"+ data.getJSONArray("data").length()); //exception here too
for(int m = 0; m < data.length(); m++){
// for(int s = 0; s < data[m].ge)
}
} catch (JSONException j){
j.printStackTrace();
}
Any pointers to create hashmap respective type I have. Appreciated
If you're trying to access the type field of a datum object, you'll want something like this:
JSONObject data = new JSONObject(dataInfo); // get the entire JSON into an object
JSONObject info = data.getJSONObject("information"); // get the 'information' object
JSONArray dataArray = info.getJSONArray("data"); // get the 'data' array
for (int i = 0; i < dataArray.length(); i++) {
// foreach element in the 'data' array
JSONObject dataObj = dataArray.getJSONObject(i); // get the object from the array
JSONObject datum = dataObj.getJSONObject("datum"); // get the 'datum' object
String type = datum.getString("type"); // get the 'type' string
if ("Student".equals(type)) {
// do your processing for 'Student' here
}
}
Note that you'll have to deal with exception handling, bad data, etc. This code just shows you the basics of how to get at the data that you're looking for. I separated each individual step into its own line of code so that I could clearly comment what is happening at each step, but you could combine some of the steps into a single line of code if that is easier for you.
if dataInfo is the json you posted, then you have to access information and from information, you can access data:
JSONObject data = new JSONObject(dataInfo);
JSONObject info = data.optJSONObject("information");
if (info != null) {
JSONArray dataArray = info.optJSONArray("data")
}

Categories

Resources