I want to convert this web service string to JSONArray , but it seems to have a problem , although I've validated it.
[
{
"hireDate": null,
"homePhoneNumber": null,
"gender": null,
"city": null,
"mobileNumber": null,
"idNumber": 123,
"religion": null,
"leftOver": 1,
"annualVacations": 5,
"dob": null,
"name": null,
"rank": 0,
"id": 1,
"workingHours": [],
"email": "ayman.daraghmah#exalt.ps",
"managers": [],
"alternativeMobileNumber": null,
"activated": true,
"username": "ayman.daraghmah#exalt.ps"
},
{
"hireDate": null,
"homePhoneNumber": null,
"gender": null,
"city": null,
"mobileNumber": null,
"idNumber": 123,
"religion": null,
"leftOver": 1,
"annualVacations": 5,
"dob": null,
"name": null,
"rank": 0,
"id": 11,
"workingHours": [],
"email": "aymandaraghmah#gmail.com",
"managers": [],
"alternativeMobileNumber": null,
"activated": true,
"username": "aymandaraghmah#gmail.com"
}
]
My Code:
JSONArray js = new JSONArray(payload);
what should the format of payload be to create the JSONArray ?
Looking at the code it looks like it should work. Following sample worked for me (The JSON is taken as a string for testing).
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) throws JSONException {
String test = "[{\"hireDate\": null,\"homePhoneNumber\": null,\"gender\": null,\"city\": null,\"mobileNumber\": null,\"idNumber\": 123,\"religion\": null,\"leftOver\": 1,\"annualVacations\": 5,\"dob\": null,\"name\": null,\"rank\": 0,\"id\": 1,\"workingHours\": [],\"email\": \"ayman.daraghmah#exalt.ps\",\"managers\": [],\"alternativeMobileNumber\": null,\"activated\": true,\"username\": \"ayman.daraghmah#exalt.ps\"},{\"hireDate\": null,\"homePhoneNumber\": null,\"gender\": null,\"city\": null,\"mobileNumber\": null,\"idNumber\": 123,\"religion\": null,\"leftOver\": 1,\"annualVacations\": 5,\"dob\": null,\"name\": null,\"rank\": 0,\"id\": 11,\"workingHours\": [],\"email\": \"aymandaraghmah#gmail.com\",\"managers\": [],\"alternativeMobileNumber\": null,\"activated\": true,\"username\": \"aymandaraghmah#gmail.com\"}]";
JSONArray jsonArray = new JSONArray(test);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
System.out.println(explrObject.getString("username"));
}
}
}
I would recommend you to follow this link to get your problem solve.
http://www.java67.com/2016/10/3-ways-to-convert-string-to-json-object-in-java.html
Related
I have a DataResponseDto.json
{
"data": [
{
"customRule": {
"code": null,
"executionType": "ON_SUCCESS",
"description": "Description",
"owners": null,
"type": "TWO",
"enabled": true,
"objectType": "TEST",
"syncObjectKPIs": null,
"inactive": false,
"responsible": null,
"id": "0AB58A47D3A64B56A6B74DA0E66935DD",
"embedded": true,
"value": null,
"variables": [],
"kafkaEventName": null,
"lastChanged": 1530091858490,
"createPerson": null,
"externalId": null,
"groups": null,
"eventType": "UPDATE",
"branches": null,
"executionOrder": null,
"createDateTime": null,
"cronExpression": null,
"udfMetaGroups": null,
"name": "Sample1",
"location": null,
"permissionsType": "USER",
"udfValues": null,
"conditions": null,
"actions": [
{
"name": "ChecklistInstance",
"parameters": {
"templateName": "checklist"
}
}
],
"syncStatus": "IN_CLOUD",
"executionLog": []
},
"customRule": {
"code": null,
"executionType": "ON_SUCCESS",
"description": "Description",
"owners": null,
"type": "TWO",
"enabled": true,
"objectType": "TEST",
"syncObjectKPIs": null,
"inactive": false,
"responsible": null,
"id": "5033296D138C45C385AC141E1157B4FE",
"embedded": true,
"value": null,
"variables": [],
"kafkaEventName": null,
"lastChanged": 1530091858490,
"createPerson": null,
"externalId": null,
"groups": null,
"eventType": "UPDATE",
"branches": null,
"executionOrder": null,
"createDateTime": null,
"cronExpression": null,
"udfMetaGroups": null,
"name": "Sample2",
"location": null,
"permissionsType": "USER",
"udfValues": null,
"conditions": null,
"actions": [
{
"name": "ChecklistInstance",
"parameters": {
"templateName": "checklist"
}
}
],
"syncStatus": "IN_CLOUD",
"executionLog": []
}
}],
"pageSize": 1,
"currentPage": 0,
"lastPage": 0,
"totalObjectCount": 1,
"truncated": false
}
And I have a class to map this JSON file.
public class DataResponseDto {
private List<Map> data;
private Integer pageSize;
private Integer currentPage;
private Integer lastPage;
private Long totalObjectCount;
private Boolean truncated;
// getter setter
...
}
Now I am using ObjectMapper to parse this JSON into a java class. It retrieved DataResponseDto with only 1 map in data. It should be 2 maps in data.
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource("mock/DataResponseDto.json").getFile());
ObjectMapper mapper = new ObjectMapper();
DataResponseDto dataResponseDto = mapper.readValue(file, DataResponseDto.class);
List<RuleDto> rules = dataResponseDto.getData().stream().map(m -> mapper.convertValue(m.get("customRule"), RuleDto.class)).collect(Collectors.toList());
I am getting rules.size() = 1, it should be 2
Your problem is with the private List<Map> data;
Map cannot have duplicate keys, consider using something else such as MultiKeyMap from apache commons (org.apache.commons.collections.map.MultiKeyMap).
You have duplicate keys customRule. Try to make customRules an array with the rules and re-run the code.
I would like to merge all the below objects as a single object recursively. Every time I run the code for every iteration I receive a string object, I am storing them in a list. List looks like below:
bean [String1, String2, String3]. These three strings are to be merged as a single string object.
String1:
[code=100,
response=
{
"testObjects": [
{
"updated": [
{
"attributes": {},
"id": "123"
},
{
"attributes": {},
"id": "456"
}
],
"timeCheckQuery": null,
"query": null,
"message": null,
"error": null,
"deleted": null,
"agentId": null,
"added": null
}
],
"message": null,
"error": null
}
]
String2:
[code=100,
response=
{
"testObjects": [
{
"updated": [
{
"attributes": {},
"id": "789"
},
{
"attributes": {},
"id": "759"
}
],
"timeCheckQuery": null,
"query": null,
"message": null,
"error": null,
"deleted": null,
"agentId": null,
"added": null
}
],
"message": null,
"error": null
}
]
String3:
[code=100,
response=
{
"testObjects": [
{
"updated": [
{
"attributes": {},
"id": "242"
},
{
"attributes": {},
"id": "951"
}
],
"timeCheckQuery": null,
"query": null,
"message": null,
"error": null,
"deleted": null,
"agentId": null,
"added": null
}
],
"message": null,
"error": null
}
]
output:
[code=300,
response=
{
"testObjects": [
{
"updated": [
{
"attributes": {},
"id": "123"
},
{
"attributes": {},
"id": "456"
},
{
"attributes": {},
"id": "789"
},
{
"attributes": {},
"id": "759"
},
{
"attributes": {},
"id": "242"
},
{
"attributes": {},
"id": "951"
}
],
"timeCheckQuery": null,
"query": null,
"message": null,
"error": null,
"deleted": null,
"agentId": null,
"added": null
}
],
"message": null,
"error": null
}
]
You could serialize the first object as a json string, then append that string with next object serialized and so on.
The value of the 'updated' field seems to be a JsonArray Structure.
What you have to do is have a Global Array that adds the values(value of the 'updated' field) from all the responses into a single JsonArray.
Using Gson Library you can do it as follows
JsonArray jsonarray = new JsonArray();
jsonarray.addAll(jsonObject1.get("updated").getAsJsonArray());
jsonarray.addAll(jsonObject2.get("updated").getAsJsonArray());
jsonarray.addAll(jsonObject2.get("updated").getAsJsonArray());
Now you can use this JsonArray inside any object as you need as your requirement needs.
I am integrating Stripe Payment module in my application. In that I use this Stripe Library.
Now using this code I generating token. Using this token I need card id before payment.
How to get this card id'. ?
Here I show you response of Stripe.
When I enter Card Information about the card Like this :
Stripe_Token::create(array(
"card" => array(
"number" => "4242424242424242",
"exp_month" => 8,
"exp_year" => 2015,
"cvc" => "314"
)
));
After that Stripe give me this response :
{
"id": "tok_14WdJ02eZvKYlo2CyaZ49ZP7",
"livemode": false,
"created": 1409272314,
"used": false,
"object": "token",
"type": "card",
"card": {
"id": "card_14WdJ02eZvKYlo2C5nE5XjtP",
"object": "card",
"last4": "4242",
"brand": "Visa",
"funding": "credit",
"exp_month": 8,
"exp_year": 2015,
"fingerprint": "Xt5EWLLDS7FJjR1c",
"country": "US",
"name": null,
"address_line1": null,
"address_line2": null,
"address_city": null,
"address_state": null,
"address_zip": null,
"address_country": null,
"customer": null
}
}
Before payment and after token created
I need this card id :
"card": {
"id": "card_14WdJ02eZvKYlo2C5nE5XjtP",
}
Hope you get my question.
As you can see in the response from stripe, you can simple get your card id and all other fields from the token object you get in response as follows:
String card_id = token.getCard().getId(); // to get card id
String id = token.getId(); // to get this "id": "tok_14WdJ02eZvKYlo2CyaZ49ZP7"
boolean live_mode = token.getLivemode(); // to get livemode
String last_four = token.getCard().getLast4(); // to get last 4
where token is the response object.
After Generating token
Use this...
Customer.all(new HashMap<String, Object>());
Using this finally i got Cardid which i want.
Here is the total response of Customer.
{
"data": [
com.stripe.model.Customer JSON: {
"object": "customer",
"created": 1410001523,
"id": "cus_4j9JlwfZ5arO4M",
"livemode": false,
"description": null,
"email": "customer#example.com",
"delinquent": false,
"metadata": {
},
"subscriptions": {
"object": "list",
"total_count": 0,
"has_more": false,
"url": "/v1/customers/cus_4j9JlwfZ5arO4M/subscriptions",
"data": [
]
},
"discount": null,
"account_balance": 0,
"currency": "usd",
"cards": {
"object": "list",
"total_count": 1,
"has_more": false,
"url": "/v1/customers/cus_4j9JlwfZ5arO4M/cards",
"data": [
{
"id": "card_14Zh0M2eZvKYlo2CAl9gQ262",
"object": "card",
"last4": "4242",
"brand": "Visa",
"funding": "credit",
"exp_month": 12,
"exp_year": 2015,
"fingerprint": "Xt5EWLLDS7FJjR1c",
"country": "US",
"name": "akinci_yasin#hotmail.com",
"address_line1": null,
"address_line2": null,
"address_city": null,
"address_state": null,
"address_zip": null,
"address_country": null,
"cvc_check": null,
"address_line1_check": null,
"address_zip_check": null,
"customer": "cus_4j9JlwfZ5arO4M"
}
]
},
"default_card": "card_14Zh0M2eZvKYlo2CAl9gQ262"
},
#<com.stripe.model.Customer[...] ...>,
#<com.stripe.model.Customer[...] ...>
],
"has_more": false
}
Hope it may help for You.
Thanks
Using gson:
package gson.sample.one;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class gsonsample
{
public class card {
public String id;
public String object;
public String last4;
public String brand;
public String funding;
public int exp_month;
public int exp_year;
public String fingerprint;
public String country;
public String name;
public String address_line1;
public String address_line2;
public String address_city;
public String address_state;
public String address_zip;
public String address_country;
public String customer;
}
public class Response {
public String id;
public Boolean livemode;
public int created;
public String object;
public String type;
public card card;
}
public static void main(String [] args)
{
String json = "{ \"id\": \"tok_14WdJ02eZvKYlo2CyaZ49ZP7\", \"livemode\": false, \"created\": 1409272314, \"used\": false, \"object\": \"token\", \"type\": \"card\", \"card\": { \"id\": \"card_14WdJ02eZvKYlo2C5nE5XjtP\", \"object\": \"card\", \"last4\": \"4242\", \"brand\": \"Visa\", \"funding\": \"credit\", \"exp_month\": 8, \"exp_year\": 2015, \"fingerprint\": \"Xt5EWLLDS7FJjR1c\", \"country\": \"US\", \"name\": null, \"address_line1\": null, \"address_line2\": null, \"address_city\": null, \"address_state\": null, \"address_zip\": null, \"address_country\": null, \"customer\": null } }";
//
Gson gson = new GsonBuilder().create();
Response response = gson.fromJson(json, Response.class);
String id = response.card.id;
System.out.println(id);
}
}
Stripe also has these objects defined in the model definitions of their Java API and usage examples in their unit tests.
I have a REST service which consumes "test/plain", basically the string I receive is a JSON string, I have the following code to parse the JSON string to DBObject so that I can save it to MongoDB.
#Timed
#POST
#Consumes("text/plain")
#Produces(MediaType.APPLICATION_JSON)
public Response insertscreenview(String message) {
// System.out.println(message);
final Logger logger = LoggerFactory.getLogger(ScreenviewResource.class);
logger.info("Screenview Insert Request Recieved" + "\n" + message);
screenviewInstance = new Screenview();
tracInfoInstance = new TracInfo();
BasicDBObject ageRangeId;
GeoCheckManager geoCheckInstance = new GeoCheckManager();
boolean brCheck;
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(message);
System.out.println(message);
DBObject objInstance = (DBObject)JSON.parse(message);
...}
My JSON string look's as follow
{
"Screenview": {
"TracInfo": null,
"Id": 0,
"ScreenName": "SettingsActivity",
"Timestamp": "2014-07-02T18:50:10",
"Timezone": "Asia/Kolkata",
"ApplicationId": null,
"DeviceId": null,
"UserId": null,
"SessionId": "5684ae84-9a48-49a5-ab47-fcb7de3c08cf"
},
"Session": {
"Id": "5684ae84-9a48-49a5-ab47-fcb7de3c08cf",
"StartTime": "2014-07-02T13:20:58",
"EndTime": "2014-07-02T13:21:09",
"EntryScreen": "AccessPointActivity",
"ExitScreen": "SettingsActivity",
"FirstEvent": "SCREEN STARTED",
"LastEvent": "SCREEN STOPPED",
"ApplicationId": "fa41f204bfc711e3b9f9c8cbb8c502c4",
"DeviceId": "0_6e505bcbe7e511e393b60aba4a7caa0b",
"UserId": "",
"TracInfoId": -1,
"SensorsInfo": null
},
"CustomParams": {
"Latitude": 0,
"Longitude": 0,
"Country": null,
"CountryCode": null,
"Region": null,
"RegionCode": null,
"City": null,
"Gender": null,
"Age": 0,
"Platform": "Android",
"OSVersion": "16",
"Manufacturer": "samsung",
"Resolution": "600 * 976",
"NetworkCarrier": null,
"Timezone": null
} }
It gives me error as follow and I am unable to find why.
java.lang.ClassCastException: java.util.HashMap cannot be cast to
com.mongodb.DBObject
Instead of using DBObject, you could make use of BasicDBObject which has a constructor taking Map as input:
BasicDBObject obj= new BasicDBObject(JSON.parse(message));
or using ObjectMapper:
BasicDBObject obj = mapper.readValue(message, BasicDBObject.class);
More up to date way of parsing a string to a DBObject:
BasicDBObject dbObject = com.mongodb.BasicDBObject.parse(rawJsonString)
Note that this should probably only be used for free schemas json objects, most of the time something like Springs MongoDBTemplate/MongoRepository etc. can be used to take care of the mapping.
I have this JSON result page, i want to parse it in .java
[
{
"kind": "track",
"id": 12429087,
"created_at": "2011/03/23 19:10:55 +0000",
"user_id": 2297976,
"duration": 473257,
"commentable": true,
"state": "finished",
"original_content_size": 19029935,
"sharing": "public",
"tag_list": "",
"permalink": "adikta-llega-la-calma-en-vivo",
"streamable": true,
"embeddable_by": "all",
"downloadable": true,
"purchase_url": null,
"label_id": null,
"purchase_title": null,
"genre": "",
"title": "ADIKTA - LLEGA LA CALMA en vivo 6",
"description": "",
"label_name": "",
"release": "",
"track_type": "",
"key_signature": "",
"isrc": "",
"video_url": null,
"bpm": null,
"release_year": null,
"release_month": null,
"release_day": null,
"original_format": "mp3",
"license": "all-rights-reserved",
"uri": "http://api.soundcloud.com/tracks/12429087",
"user": {
"id": 2297976,
"kind": "user",
"permalink": "adikta",
"username": "adikta",
"uri": "http://api.soundcloud.com/users/2297976",
"permalink_url": "http://soundcloud.com/adikta",
"avatar_url": "http://i1.sndcdn.com/avatars-000002155791-15emwj-large.jpg?3eddc42"
},
"permalink_url": "http://soundcloud.com/adikta/adikta-llega-la-calma-en-vivo",
"artwork_url": "http://i1.sndcdn.com/artworks-000005792200-72zfn4-large.jpg?3eddc42",
"waveform_url": "http://w1.sndcdn.com/hPYrb5G8V4an_m.png",
"stream_url": "http://api.soundcloud.com/tracks/12429087/stream",
"download_url": "http://api.soundcloud.com/tracks/12429087/download",
"playback_count": 114,
"download_count": 19,
"favoritings_count": 1,
"comment_count": 0,
"attachments_uri": "http://api.soundcloud.com/tracks/12429087/attachments"
},
this is my .java class (android) code:
try {
JSONObject respObj = new JSONObject(result);
JSONObject topTracksObj = respObj.getJSONObject("tracks");
JSONArray tracks = topTracksObj.getJSONArray("track");
for(int i=0; i<tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String trackName = track.getString("permalink");
String trackUrl = track.getString("permalink_url");
JSONObject artistObj = track.getJSONObject("user");
String artistName = artistObj.getString("permalink");
String artistUrl = artistObj.getString("uri");
String imageUrl;....
But i cant find any solution to parse or navigate in this JSON directory without ids.
the api im using is soundcloud, but i cant find the answer there either. any help would be appreciated.
any suggestion?
thanks in advance
Kindly find the below mentioned code:
String str = "<YOUR_JSON_STRING>";
JSONArray jArrayObject;
try {
jArrayObject = new JSONArray(str);
for (int i = 0; i<jArrayObject.length(); i++) {
Log.d("kind==", jArrayObject.getJSONObject(i).getString("kind").toString());
Log.d("id==", jArrayObject.getJSONObject(i).getString("id").toString());
Log.d("created_at==", jArrayObject.getJSONObject(i).getString("created_at").toString());
JSONObject jObj = new JSONObject(jArrayObject.getJSONObject(i).getString("user").toString());
Log.d("id==", jObj.getString("id").toString());
Log.d("kind==", jObj.getString("kind").toString());
Log.d("permalink==", jObj.getString("permalink").toString());
Log.d("username==", jObj.getString("username").toString());
Log.d("permalink_url==", jObj.getString("permalink_url").toString());
Log.d("avatar_url==", jObj.getString("avatar_url").toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}