retrieving values from nested JSON in java - java

I have a JSON which is mentioned below.
{"Orders"
[{"BusinessUnit":"TS",
"DeliveryDetails":
[{"SlotStartDateTime":"2015-03-30T16","DeliveryOption":"Home
Delivery","ReservationID":"13349259","PersonInfoShipTo":
{"Address":"OrganizationName":"HP","BuildingTypeID":"",
"IsCommercialAddress":"false","PostalCode":"56001",
"City":"Bangalore","AddressLine3":"A3","AddressLine2":"A2",
"AddressLine1":"A1","IsPAFValidated":"true",
"GridRef":"0473601734","State":"KA","AddressLine4":"A4",
"Country":"IN"}},"ShipNode":"NODEUK","SlotEndDateTime":"2015-
03-30T17"}],
"FulfilmentID":"a9466f83-938d-4115-a3d4-62ff4bdcd1b6",
"OrderTypeIndicator":"SalesOrder"}]}
Question:
I am able to take the values of BusinessUnit, FulfilmentID & OrderTypeIndicator. But, I am unable to take the values present inside the inner json object DeliveryDetails. Could anyone help me on taking those values

"DeliveryDetails" is mapped to a json array object with a single json object inside.
Try doing:
json.getJSONArray("Orders").get(0).get("DeliveryDetails").get(0)
Of course it would be better to check first if keys exists and the size of json arrays returned before retrieving actual indices.

Related

how to represent a list of entity values in JSON object

I have a list of records in a entity type ,i had a confusion the way how to represent in column wise list or each of record as a json object,that means list of JSON Objects.
::Explanation ::
Here firstName,secondName,thirdName are column names.
Need To Represent Like this format
__{{firstName:Rec1,secondName:Rec1,thirdName:Rec1},{firstName:Rec2,secondName:Rec2,thirdName:Rec2}...n}__
But i approached like
__{firstName:[Rec1,Rec2,Rec3...],secondName:[Rec1,Rec2,Rec3...],thirdName:[Rec1,Rec2,Rec3...]},__
When i tried to pass as a entity type means it shows like
__{"ServiceData":[com.aiway.eea.ejb.to.student.ParentStudentDetailsTO#8b0db2,com.aiway.eea.ejb.to.student.ParentStudentDetailsTO#1304967]}__
Please Help me to solve this...
we not able to pass as a entity type,we need Transfer Object to convert from ENTITY to JSON object,if List entityType means then Use List JSONObject and then put that List of JsonObject to another Json object like <"serviceData":JsonObject> then it will OUTPUT like
{"ServiceData":[{"parentId":4009,"parentRelation":"Father","‌​parentNotification":‌​false,"parentOccupat‌​ion":"bussiness","pa‌​rentEducation":"mba"‌​,"parentName":"tharu‌​n"},{"parentId":4010‌​,"parentRelation":"M‌​other","parentNotifi‌​cation":false,"paren‌​tOccupation":"sdfsdf‌​","parentEducation":‌​"sdfsdfs","parentNam‌​e":"rakshitha"}]}
You can retrive like the Example syntax
See The Example From this IMAGE Link....
use this Link to lean about JSON Array
https://www.w3schools.com/js/js_json_arrays.asp

Converting JSON Object(s) from file using Java

I have a JSON file with no clue on how data will be in it nor the structure of data.
The only thing known is that it will have either an array of JSON objects or a single JSON object.
I need to get each object from the file and store it as a separate item. In case of array of objects in the file, I should get an array of JSON strings which I can store in DB.
Basically, I need to read this file and separate out each JSON object from it and store it in DB as a string.
One of the ways to do it was to use JACKSON ObjectMapper and assign these items to a Hashmap as key value pairs, but I am not sure though how it can be done If there are list of JSON Objects in the file.
Sample JSON File:
[
{
"name":"Bob",
"type":"Email",
"from":"a#a.com",
"to":"b#B.com",
"attachments":[...],
.
.
.
}
]
Do you know the Object structure that the JSON has(let it be Array or a single one) ? If Yes,
First load the json string form the file into an in memory string.
check the string for Array existence, by searching for '[',']' in the outer structure of multiple occurrences of '{' or '}'
once you know whether you have an array or a single object, you can pass it as object reference to either Jackson or GSON parsers
create in memory Array of JsonObject.class say List. It is actually better to enclose this List inside another class. say myJsonObjects and have a List inside it.
Let us see GSON parsers (by google), though Jackson can also be used in the similar implementation
Gson gson = new Gson();
if(isArray){
myJsonObjects jsonArray = gson.fromJson(jsonStringFromFile,myJsonObjects );
}
else{
gson.fromJson(jsonStringFromFile,JsonObject);
}
http://google-gson.googlecode.com/svn-history/trunk/gson/docs/javadocs/com/google/gson/Gson.html
Jackson is my favorite JSON-to-POJO library. It doesn't really matter where you're loading the JSON from (a URL or from the filesystem), there are handlers for several input sources.
Here's an example:
Map<String,Object> userData = mapper.readValue(new File("user.json"), Map.class);
As far as having an unknown number of JSON structures that you're about to parse, the first thing that comes to mind is to have a mapper for each type you're expecting. You could then wrap the parsing code in try/catch blocks so that if the first fails with whatever exception Jackson gives you when encountering an unexpected format, you can then try the next format and so on.
If you're just trying to generically parse JSON that you don't know the structure of beforehand, you can try something like this:
mapper.readValue(jsonString, new TypeReference<List<EntryType>>() {});
The documentation for Jackson is pretty good-- giving it a solid read-through should definitely help. Here's a good five minute tutorial: http://wiki.fasterxml.com/JacksonInFiveMinutes
I prefer use Gson:
Gson gson;
Map<String, Object>parameters=gson.fromJson(myString);
the rest is iterate the map, i hope help you

How can I convert from java ArrayList object to real value

I'm trying to get a value from the databae.
My Database query:
String GroupID1="select idCompanies from companies where Company_Name='ACME';";
here I'm calling to a javabeans which give back an ArrayLIst with one element
ArrayList<?> IdGroup1=oper.getList(GroupID1);
then, I print the result:
System.out.println(IdGroup1);
The query works fine, however I'm getting as a result:
[javabeans.ListOneElement#609f6e68]
Instead of the real value. How can I convert the java object to the real value?
you are printing the ArrayList object IdGroup1,You need to iterate to get the alues
This code will retrieve the first (and only) item from the list:
System.out.println(IdGroup1.get(0).toString());
Adding the following will prevent a nullPointerException:
if (!IdGroup1.isEmpty())
System.out.println(IdGroup1.get(0).toString());
-Added .toString() to get the value of the object
Consider what type of Object oper.getList(GroupID1) will return.
You need to accommodate for whatever object that is and then convert it to String.
You need to:
Unpackage your list (that is a list contains, and is expected by java to possibly contain multiple objects, so it doesn't automatically 'unpack' it for you if you have a list of 1 object)
Extract your string. Here java might cleverly convert a number (int, float, etc. ) to a string for you.
For part two, look at what you expect the object to be by finding the JavaDocs for whatever package is handling your database queries. Then see how to extract your string.
It might be as simple as System.out.println(IdGroup1.get(0).toString());
Where get(0) unpackages the object from the list, and toString() extracts the string.
If you still get back javabeans.ListOneElement#41ccdc4d try other methods to extract your string....toValue() perhaps? It depends on the packages you're using.

JSONObject.append - result is nested array?

I have seen this question and understand the answer, but can not use it in my scenario.
My scenario: I retrieve data via JPA from a mysql database and want to put this data into a JSONObject like this
{
"A":["1","2","3"],
"B":["1","2","3","4"],
"C":["1","2"]
}
The problem is I do not know how many arrays I will retrieve. It could be 1 or it could be 200, depending on the data in the database.
If I append the data into a JSONObject like this:
import org.apache.tapestry5.json.JSONObject
// ...
JSONObject data = new JSONObject();
for (Value val : values) data.append(val.getName(), val.getValue());
I'll get
{"val_name": [[["1"],"2"],"3"], ...}
Is there a way to use JSONOBject.append without creating JSONArrays and puting them into the JSONObject, which will result in a nested JSONObject?
A JSON object is a "dictionary" -- a map between name and value. A JSON array is a sequential list of values, with only the ordinal position of the value identifying it. It makes no sense to "append" to the object -- you add new name/value pairs to it (although they apparently call it appending, just to confuse you). If, within an object, you want something like "A":["1","2","3"] then you necessarily must insert an array (as the value of a name/value pair) into the object.
But note that either before inserting the array into the object or after you can append additional values to the array. You just need to get/save a reference to the array.
In your above example you're making the mistake of appending to the object rather than the array.

ArrayList is changing index order after copying content of a JSON object

Lets say that I have a JSON object called fruits and this is the content of it:
"fruits":[{
"name":"natural_one",
"kind"{
0:"apple",
1:"banana",
2:"pear"
}
}];
And when I copy the content of the JSONObject in a new ArrayList, the index order changes like the example here below:
"fruits":[{
"kind"{
1:"banana",
2:"pear",
0:"apple"
},
"name":"natural_one"
}];
What do I do to prevent changing index order when copying content takes place?
I'm not sure this is your problem, but JSON object properties don't have any intrinsic order.
{"a":"b",
"c":"d"}
is strictly equivalent to
{"c":"d",
"a":"b"}
Can someone give me an example how to copy the content of a JSONObject without changing the index order?
It is not possible.
The JSONObject class stores the attributes in a hash table, so is not capable of representing the ordering of the attributes in a serial JSON representation. That's OK because, the JSON spec says that the order of the attributes is not significant.
This comes from the origin of JSON, which is Javascript stntax for associative arrays / objects. The entries in a Javascript associative have no defined / significant order.

Categories

Resources