I'm trying to read data from .dat files & then write them in .json. The problem is some persons have no emails in files. So, I want something like
"emails": []
{
"personCode": "2342",
"firstName": "Jeff",
"lastName": "Spalding",
"address": {
"street": "123 Friendly Street",
"city": "Ottawa",
"state": "ON",
"zip": "K1A 0G9",
"country": "Canada"
},
"emails": []
},
However, my code prints no emails[]
{
"personCode": "2342",
"firstName": "Jeff",
"lastName": "Spalding",
"address": {
"street": "123 Friendly Street",
"city": "Ottawa",
"state": "ON",
"zip": "K1A 0G9",
"country": "Canada"
}
}
My code:
String[] email = null;
String[] emailTokens = data[3].split(",");
for (int i = 0; i < emailTokens.length; i++) {
email = emailTokens;
}
Person person = new Person(personCode, firstName, lastName, address, email);
personList.add(person);
Any idea? Thanks!
Your loop doesn't make sense:
for (int i = 0; i < emailTokens.length; i++) {
email = emailTokens; // Here you assign the some emailTokens N times.
}
It can be simplified to:
String[] email = data[3].split(",");
Regarding your question about missed email in the JSON, try to pass empty array:
String[] email = data[3].split(",");
if (email == null) {
email = new String[0];
}
Related
I have define List of HashMap and reading the response of JSON API . Currently able to read only one value from the list and I want to read all the values.
List<HashMap<String,Object>> allids = response.jsonPath().getList("data");
HashMap<String,Object> firstid = allids.get(0);
Object a = firstid.get("country");
System.out.println(a);
JSON Response in PostMan
{
"response": {
"code": 200,
"status": "success",
"alert": [
{
"message": "Success",
"type": "success",
"skippable": 1
}
],
"from_cache": 0,
"is_data": 1
},
"data": [
{
"id": 6004,
"airport_name": "Adampur Airport",
"city": "Adampur",
"country": "India",
"iata": "AIP",
"icao": "VIAX",
"latitude": "31.4338",
"longitude": "75.758797",
"altitude": "775"
}
]
}
Just forEach on your List you will get Map and then get all your Object bu using get .
List<HashMap<String,Object>> allids = response.jsonPath().getList("data");
allids.forEach(elem->{
String country = (String) elem.get("country");
String city = (String) elem.get("city");
// and so on.
});
Judging from the context, you can iterate over the list and get the Map values
List<HashMap<String,Object>> allids = response.jsonPath().getList("data");
for(int i=0; i<allids.size(); i++){
HashMap<String,Object> firstid = allids.get(i);
String country = (String) firstid.get("country");
String city = (String) firstid.get("city");
String iata = (String) firstid.get("iata");
String altitude = (String) firstid.get("altitude");
//similarly get others
System.out.println(country);
}
May be it's a simple task for some one.
I've json like below.
{
"address": {
"state": "World",
"address": "infinite space, 000",
"city": "Android city",
"address2": {
"state": "World2",
"address": "infinite space2, 002",
"city": "Android city2",
"address3": {
"state": "World3",
"address": "infinite space3, 003",
"city": "Android city3"
}
}
},
"valid": {
"state": "World",
"address": "infinite space, 000",
"city": "Android city",
"valid2": {
"state": "World2",
"address": "infinite space2, 002",
"city": "Android city2",
"valid3": {
"state": "World3",
"address": "infinite space3, 003",
"city": "Android city3"
}
}
}
}
This is a sample structure. Some times may have many objects inside of one object. I know this is a bad format of JSON but i've to achieve my requirement by using this only :-(.
My requirement is: when we sending the object name like address3 or valid3 to a method as argument. My method have to return key and value of object (Which we passed as argument). Any one know, how to achieve this in Java?
You can parse the JSON and convert the result into a HashMap<String,String>
Here is sample code for this JSON object .
public HashMap<String,String> getKeyValuePairs(JSONObject json,String key){
HashMap<String,String> jsonHashList=new HashMap<String,String>();
JSONObject desiredJSON = json.get(key);
Iterator<?> keys = desiredJSON.keys();
while( keys.hasNext() ) {
String key2 = (String)keys.next();
if ( desiredJSON.get(key2) instanceof JSONObject ) {
String value = desiredJSON.get(key2);
jsonHashList.add(key2,value);
}
}
return jsonHashList;
}
Note : In this case key is assumed to be at level one of passed JSON so if you want to pass any JSON to get it's key values separated pass the Level One JSON.
This is the solution
private void parseJson(JSONObject jsonObject, String objName){
try {
for(int i = 0; i < jsonObject.length(); i++){
if(jsonObject.get(jsonObject.names().getString(i)) instanceof JSONObject){
JSONObject singleObj = new JSONObject(jsonObject.get(jsonObject.names().getString(i)).toString());
Iterator<String> keys= singleObj.keys();
while (keys.hasNext()){
String keyValue = keys.next();
final String valueString = singleObj.getString(keyValue);
if(!isJSONObjectOrString(valueString)){
if(keyValue.contains(objName) || valueString.contains(objName)
|| jsonObject.names().getString(i).contains(objName)){
Log.e("objectName", jsonObject.names().getString(i));
Log.e(keyValue, valueString);
}
}
}
parseJson(singleObj);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
Here's the JSON:
{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "123 Main street",
"city": "Anytown",
"postalCode": "12345"
},
"phoneNumbers": [
{
"type": "iPhone",
"number": "123-456-8888"
},
{
"type": "home",
"number": "123-557-8910"
}
]
}
The question is, in Java, how do you access the address fields? I tried things like address.city, but that didn't work:
String city = (String) jsonObject.get("address.streetAddress");
System.out.println(city);
Would appreciate any suggestions.
You need to call getString on the address object that you get.
String city = jsonObject.getJSONObject("address").getString("streetAddress");
{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "123 Main street",
"city": "Anytown",
"postalCode": "12345"
},
"phoneNumbers": [
{
"type": "iPhone",
"number": "123-456-8888"
},
{
"type": "home",
"number": "123-557-8910"
}
]
}
first get your address.Address is an object.{} means object,[] means an array.
JSONObject addressObj = jsonObject.get("address");
now you have a reference to the address.
String addressStr = addressObj.get("streetAddress");
String cityStr = addressObj.get("city");
int cityInt = Integer.parseInt(addressObj.get("postalCode"));
If i don't wrong remember there should be getString("streetAddress") and getInteger("postalCode") to avoid parse issues.
Apart from the given answers you should add a check to see if the address is not blank before checking city or else you will end up getting and exception.
Here is updated example:
if( jsonObject.has("address"){
JSONObject addressObj = jsonObject.get("address");
if( addressObj.has("city"){
String cityStr = addressObj.get("city");
}
}
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");
String age=res.getString("age");
.
.
jsonObject.put("Name", Name);
jsonObject.put("age", age);
.
.
ja.put(jsonObject);
}
mainjsonObject.put("PERSONAL DETAILS",ja);
I should get the output json as follows(i.e. the order in which i entered):
{
"PERSONAL DETAILS": [
{
" name": "abc",
"age": "4",
"gender": "F",
"Place": "abc1"
},
{
" name": "xyz",
"age": "3",
"gender": "M",
"Place": "abc2"
}
]
}
But am getting the values in random order like below:
{
"PERSONAL DETAILS": [
{
"age": "4",
" name": "abc",
"Place": "abc1"
"gender": "F",
},
{
"age": "3",
" name": "xyz",
"Place": "abc2"
"gender": "M",
}
]
}
Please help me with a solution. I need to get all the values in the same order in which i have entered.
You can try something like this to build json object construct using LinkedHashMap and then pass it to the constructor like this ,
LinkedHashMap<String, String> jsonOrderedMap = new LinkedHashMap<String, String>();
jsonOrderedMap.put("Name", res.getString(1));
...
...
// struct you want
JSONObject JSONorder = new JSONObject(jsonOrderedMap);
JSONArray sortedJSON = new JSONArray(Arrays.asList(JSONorder));
I have this json:
[{
"name": "prog 1",
"show": [{
"name": "n1",
"time": "01.10 "
}, {
"name": "n2",
"time": "01.35 "
}]
}, {
"name": "prog 2",
"show": [{
"name": "n1",
"time": "01.10 "
}, {
"name": "n2",
"time": "01.35 "
}]
}]
Now trying to parse it in Java like:
JSONObject json=new JSONObject(json_str);
throws an Exception, since it doesn't begin with {, but [ since it's an array. I can parse this without problem in js, but aparently I cannot load an JSONArray with this string...
use: JSONArray objArray = new JSONArray (json_str);
// to access the individual objects inside the array:
for(int i=0;i<objArray.length();i++)
{
JSONObject obj = objArray.getJSONObject(i);
}
Have you tried this:
JSONArray arr = new JSONArray(stringWithContent);
Then access it like :
for(int i = 0; i<arr.length();i++){
System.out.println(arr.get(i));
}
You can try following code
JSONObject jObject = new JSONObject(json_str);
JSONArray array = jObject.getJSONArray("show");
for(int i = 0 ; i < array.length() ; i++)
{
System.out.println(array.getJSONObject(i).getString("name"));
System.out.println(array.getJSONObject(i).getString("time"));
}
It will helpful ...