Here is my JAVA JSON code
#GET
#Consumes("application/x-www-form-urlencoded")
#Path("/getAllEmp")
public Response GetAllEmp() {
JSONObject returnJson = new JSONObject();
try {
ArrayList<Emp_Objects> objList = new ArrayList<Emp_Objects>();
DBConnection conn = new DBConnection();
objList = conn.GetEmpDetails();
JSONArray empArray = new JSONArray();
if (!objList.isEmpty()) {
GetLocation loc = new GetLocation();
for (Emp_Objects obj : objList) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", obj.id);
jsonObj.put("name", obj.name);
jsonObj.put("email", obj.email);
jsonObj.put("address", obj.address);
empArray.put(jsonObj);
}
}
returnJson.put("data", empArray);
} catch (Exception e) {
}
return Response.ok(returnJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
When i execute this it gives me the following json
{
"data": [{
"id": 1,
"name": "123_name"
}, {
"id": 2,
"name": "321_name",
"email": "xyz#asd.com"
}]
}
In the above json email and address are missing because email and address is null on database.
So can i show json with empty value like following
{
"data": [{
"id": 1,
"name": "123_name",
"email": "",
"address": ""
}, {
"id": 2,
"name": "321_name",
"email": "",
"address": ""
}]
}
I am using JAVA and org.json with MySQL database.
If the objects are null, insert an empty String instead.
jsonObj.put("email", obj.email == null ? "" : obj.email);
jsonObj.put("address", obj.address == null ? "" : obj.address);
If you have a larger amount of rows to process, I recommend you to turn this is to a function for better readability and to save you some time.
jsonObj.put("email", nullToEmpty(obj.address));
private String nullToEmpty(String arg) {
return arg == null ? "" : arg;
}
Related
I have a complex and nested JSON File which looks like this
{
"databases": {
"component": "pages/dems/transparency/workspaces/DatasourcesWorkspace.vue",
"children": [
{
"name": "Databases",
"path": "databases",
"component": "pages/dems/transparency/workspaces/Databases.vue",
"hide": true,
"help": "context-sensitive-help/transparency/workspaces/datasources/databases/databases/databases.html"
},
{
"name": "Schemas",
"path": "schemas",
"component": "containers/EmptyContainer.vue",
"hide": true,
"children": [
{
"name": "",
"component": "pages/dems/transparency/workspaces/Schemas.vue",
"hide": true,
"help": "context-sensitive-help/transparency/workspaces/datasources/databases/schemas.html"
},
{
"name": "",
"path": "relationship/:id",
"component": "pages/dems/transparency/workspaces/profilecolumn/ViewRelationShip.vue",
"hide": true,
"help": "context-sensitive-help/transparency/workspaces/relationship/relationship.html"
}
]
}
]
}
}
I want to insert it into MongoDB. The structure would be like this:
{
"_id":"id1",
"field":"databases",
"value":{
"component": "pages/dems/transparency/workspaces/DatasourcesWorkspace.vue",
"children": [
{
"name": "Databases",
"path": "databases",
"component": "pages/dems/transparency/workspaces/Databases.vue",
"hide": true,
"help": "context-sensitive-help/transparency/workspaces/datasources/databases/databases/databases.html"
},
{
"children": [
{
"name": "",
"component": "pages/dems/transparency/workspaces/Schemas.vue",
"hide": true,
"help": "context-sensitive-help/transparency/workspaces/datasources/databases/schemas.html"
},
{
"name": "",
"path": "relationship/:id",
"component": "pages/dems/transparency/workspaces/profilecolumn/ViewRelationShip.vue",
"hide": true,
"help": "context-sensitive-help/transparency/workspaces/relationship/relationship.html"
}
]
}
]
}
}
I need to also check if any object has the containers/EmptyContainer.vue inside the component value then do not insert that object inside MongoDB.
I have tried many methods but didn't work.
Code tried, which is not working as expected:
public ArrayList<Document> processJsonV4(Object source) throws JSONException {
ArrayList<Document> rootDoc = new ArrayList<>();
if (source instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) source;
Document document = new Document();
if (jsonObject.has("component") && !"containers/EmptyContainer.vue".equals(jsonObject.getString("component"))) {
for (Iterator keys = jsonObject.keys(); keys.hasNext(); ) {
String key = (String) keys.next();
Object value = jsonObject.get(key);
document.append(key, value);
}
} else {
for (Iterator keys = jsonObject.keys(); keys.hasNext(); ) {
String key = (String) keys.next();
Object value = jsonObject.get(key);
processJsonV4(value);
}
}
rootDoc.add(document);
}
KLogger.info("RootDoc: " + rootDoc);
return rootDoc;
}
How can I do this using Java?
A simple recursive way could be to construct and add to the list of Documents when you invoke them:
public void readAndConstructMongoDoc() {
JSONObject jsonData = readFileData("<your-file.json>");
List<Document> rootDoc = new ArrayList<>();
constructRootDoc(rootDoc, jsonData);
// Save in mongo -> rootDoc
}
private void constructRootDoc(List<Document> rootDoc, Object source) {
if (source instanceof JSONObject) {
JSONObject jsonObject = new JSONObject();
if (jsonObject.has("component") && !"containers/EmptyContainer.vue".equals(jsonObject.getString("component"))) {
rootDoc.add(convertToMongoDocument(jsonObject));
JSONArray children = jsonObject.getJSONArray("children");
int length = children.length();
for (int i = 0; i < length; i++) {
// Recursively call for all child node and pass the rootDoc
testJson(rootDoc, children.getJSONObject(i));
}
}
}
}
private Document convertToMongoDocument(JSONObject jsonObject) {
Document document = new Document();
document.append("name", jsonObject.getString("name"));
document.append("path", jsonObject.getString("path"));
document.append("hide", Boolean.valueOf(jsonObject.getString("hide")));
document.append("component", jsonObject.getString("component"));
return document;
}
Side Note: I believe your Mongo Document schema can be improvised and doesn't have to be storing the data in this format.
this is the json data and i want to display the info object using volley in android java i hope you can answer this question thank you
"data": {
"type": "customer",
"name": "Sasmple name",
"phone": "1234567",
"email": "sample#gmail.com",
"email_verified_at": null,
"created_at": "2021-05-04T08:24:49.000000Z",
"updated_at": "2021-05-04T08:24:49.000000Z",
"info": {
"id": 63,
"user_id": 381,
"fname": "Sample",
"mname": null,
"lname": "Name",
"gender": null,
"image": null,
"birthdate": null,
"address": "Sample, Sample City (capital), Sample",
"address_code": "{\"region\":\"07\",\"province\":\"0722\",\"citymun\":\"072217\",\"barangay\":\"072217027\"}",
"bank_number": "17171717171717171717",
"bank_name": "Sample bank",
"created_at": "2021-05-04T08:24:49.000000Z",
"updated_at": "2021-05-04T08:24:49.000000Z"
}
}
and this is my code that i used
JSONObject json= null;
try {
json = new JSONObject("info");
for(int i=0; i<json.length(); i++){
JSONObject item = json.getJSONObject(String.valueOf(json));
String province_id = item.getString("id");
String province_code = item.getString("fname");
String province_desc = item.getString("lname");
String province_regcode = item.getString("address");
String province_citycode = item.getString("address_code");
}
} catch (JSONException e) {
e.printStackTrace();
}
Please read more about JSON Object and Json Array here
To answer for your question
try {
JSONObject jsonData = new JSONObject(httpStringResponse);
JSONObject infoItem = json.getJSONObject("info");
String province_id = infoItem.getString("id");
String province_code = infoItem.getString("fname");
String province_desc = infoItem.getString("lname");
String province_regcode = infoItem.getString("address");
String province_citycode = infoItem.getString("address_code");
} catch (JSONException e) {
e.printStackTrace();
}
{
"reservation_upto": {
"lng": 78.0098161,
"lat": 27.1752554,
"code": "AGC",
"name": "AGRA CANTT"
},
"debit": 3,
"doj": "28-05-2018",
"to_station": {
"lng": 78.0098161,
"lat": 27.1752554,
"code": "AGC",
"name": "AGRA CANTT"
},
"response_code": 200,
"boarding_point": {
"lng": 80.2755685,
"lat": 13.081674,
"code": "MAS",
"name": "CHENNAI CENTRAL"
},
"pnr": "4405474586",
"chart_prepared": false,
"journey_class": {
"code": "3A",
"name": null
},
THIS IS WHAT I HAVE TRIED USING VOLLEY
private void loaddata() {
String url = "https://api.railwayapi.com/v2/pnr-status/pnr/4655474586/apikey/q15rfl3kpz/";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.dismiss();
JSONObject obj = null;
try {
String str="";
obj = response.getJSONObject("name");
str = String.valueOf(obj);
TextView tv = (TextView)findViewById(R.id.textView);
tv.append(str);
}
}
}
}
}
JSONObject obj = (JSONObject) object;
String doj = (String) obj.get("doj")
You can use JSONObject obj to find out the value of key doj.
Latter on, if you want to have the doj as any other datatype you can parse in that. May be this could help. I don't have much idea on Volley :)
I just tried to get values that are stored in my JSON file and save it into sqlite database:
This is my JSON file:
{
"list": {
"meta": {
"count": 132,
"start": 0,
"type": "resource-list"
},
"resources": [
{
"resource": {
"classname": "Quote",
"fields": {
"date": "2017-03-16",
"price": 3.6720000000000002,
"type": "currency",
"symbol": "AED=X"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"date": "2017-03-16",
"price": 65.075000000000003,
"type": "currency",
"symbol": "AFN=X"
}
}
},
{
.............
}
............
I have tried like this but getting exception :
JSONObject mainObj = null;
try {
mainObj = new JSONObject(JSON);
JSONObject getSth = mainObj.getJSONObject("list");
if(mainObj != null){
JSONArray list = getSth.getJSONArray("resources");
if(list != null){
for(int i = 0; i < list.length();i++){
JSONObject elem = list.getJSONObject(i);
if(elem != null){
JSONObject prods = elem.getJSONObject("fields");
Object level = prods.get("type");
Toast.makeText(getApplicationContext(),""+level.toString(),Toast.LENGTH_LONG).show();
}
}
}
}
}catch (Exception e){
Toast.makeText(getApplicationContext(),""+e.toString(),Toast.LENGTH_LONG).show();
}
I was getting exception : no values in fields...
And pls give some suggestions that storing these values in Database table(matrotable) of(row fields) name, prize, symbol and type, I may try by making String Array and retrieving and storing the values for sqlite, is there any other easy options...
thanks
your fields objects are inside resource object so do
for(int i = 0; i < list.length();i++){
JSONObject elem = list.getJSONObject(i);
if(elem != null){
JSONObject prods = elem.getJSONObject("resource")
.getJSONObject("fields");
Object level = prods.get("type");
Toast.makeText(getApplicationContext(),""+level.toString(),Toast.LENGTH_LONG).show();
}
}
"resources": [ // resources list
{ // object i
"resource": { // fields are inside "resource" object
"classname": "Quote",
"fields": {
"date": "2017-03-16",
"price": 3.6720000000000002,
"type": "currency",
"symbol": "AED=X"
}
}
}
You are missing the resource JOSNObject parsing...
for(int i = 0; i < list.length();i++){
JSONObject elem = list.getJSONObject(i);
JSONObject resource = elem.getJSONObject("resource");
if(resource != null){
JSONObject prods = resource.getJSONObject("fields");
Object level = prods.get("type");
Toast.makeText(getApplicationContext(),""+level.toString(),Toast.LENGTH_LONG).show();
}
}
I recommend to you to use the simplest and easiest way to parse a json response to avoid this kind of issues:
1- generate your model classes by using this tool: http://www.jsonschema2pojo.org/ download and add the generated classes to your model package.
2- add this dependency to your gradle file:
compile 'com.google.code.gson:gson:2.4'
3- Call this method to parse your response:
Gson gson = new Gson();
ResponseModel responseModel = gson.fromJson(json, ResponseModel.class);
I am having trouble parsing this particular JSONObject,
Here is the object:
{"status":1,"dds":{"id":1,"name":"DDS1","description":"This is DDS 1","children":[{"id":2,"order":1,"type":1,"children":[{"id":3,"order":1,"type":3,"children":[]},{"id":4,"order":2,"type":2,"children":[]}]}]}}
That object is stored in my variable called result, here is my code to parse it:
JSONObject jsonObj = null;
JSONArray jsonArr = null;
try {
jsonObj = new JSONObject(result);
jsonArr = jsonObj.getJSONArray("dds");
} catch (JSONException e) {
e.printStackTrace();
}
And it is giving me this error:
org.json.JSONException: Value {"id":1,"children":[{"type":1,"order":1,"id":2,"children":[{"type":3,"order":1,"id":3,"children":[]},{"type":2,"order":2,"id":4,"children":[]}]}],"description":"This is DDS 1","name":"DDS1"} at dds of type org.json.JSONObject cannot be converted to JSONArray
I am trying to break it up into sub arrays of children. Where am I going wrong?
#Mr Love
here is my output to your code
You are calling jsonArr = jsonObj.getJSONArray("dds");, however dds is not an array, it's a JSON object, if you format the JSON you can see it clearly:
{
"status":1,
"dds":{
"id":1,
"name":"DDS1",
"description":"This is DDS 1",
"children":[
{
"id":2,
"order":1,
"type":1,
"children":[
{
"id":3,
"order":1,
"type":3,
"children":[
]
},
{
"id":4,
"order":2,
"type":2,
"children":[
]
}
]
}
]
}
}
So you will just need to call JSONObject dds = jsonObj.getJSONObject("dds"), and if you want the children you would call JSONArray children = jsonObj.getJSONObject("dds").getJSONArray("children");.
private static final String json = "{\"status\":1,\"dds\":{\"id\":1,\"name\":\"DDS1\",\"description\":\"This is DDS 1\",\"children\":[{\"id\":2,\"order\":1,\"type\":1,\"children\":[{\"id\":3,\"order\":1,\"type\":3,\"children\":[]},{\"id\":4,\"order\":2,\"type\":2,\"children\":[]}]}]}}";
public static void main(String[] args) throws JSONException
{
JSONObject jsonObj = new JSONObject(json);
JSONObject dds = jsonObj.getJSONObject("dds");
JSONArray children = dds.getJSONArray("children");
System.out.println("Children:");
System.out.println(children.toString(4));
JSONArray grandChildren = children.getJSONObject(0).getJSONArray("children");
System.out.println("Grandchildren:");
System.out.println(grandChildren.toString(4));
}
Produces:
Children:
[{
"children": [
{
"children": [],
"id": 3,
"order": 1,
"type": 3
},
{
"children": [],
"id": 4,
"order": 2,
"type": 2
}
],
"id": 2,
"order": 1,
"type": 1
}]
Grandchildren:
[
{
"children": [],
"id": 3,
"order": 1,
"type": 3
},
{
"children": [],
"id": 4,
"order": 2,
"type": 2
}
]
You can do it like this, where the JsonElement could be a JSONobject or JsonArray or any primitive type:
private JsonElement findElementsChildren(JsonElement element, String id) {
if(element.isJsonObject()) {
JsonObject jsonObject = element.getAsJsonObject();
if(id.equals(jsonObject.get("id").getAsString())) {
return jsonObject.get("children");
} else {
return findElementsChildren(element.get("children").getAsJsonArray(), id);
}
} else if(element.isJsonArray()) {
JsonArray jsonArray = element.getAsJsonArray();
for (JsonElement childElement : jsonArray) {
JsonElement result = findElementsChildren(childElement, id);
if(result != null) {
return result;
}
}
}
return null;
}