Related
Below Json I want to get only first mail value (abc#test.com) using java. Please anybody can suggest how do I extract exact value from below Json. Thanks in advance.
{
"profiles": [
{
"userId": "1234",
"content": {
"address": {
"business": {
"country": "IN",
"locality": "Chennai",
}
},
"name": {
"first": "abc",
"last": "abc"
},
"mail": [
"abc#test.com",
"xyz#test.com"
]
}
}
]
}
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) throws JSONException {
String jsonstring = "{\"profiles\":[{\"userId\":\"1234\",\"content\":{\"address\":{\"business\":{\"country\":\"IN\",\"locality\":\"Chennai\"}},\"name\":{\"first\":\"abc\",\"last\":\"abc\"},\"mail\":[\"abc#test.com\",\"xyz#test.com\"]}}]}";
System.out.println(jsonstring);
JSONObject jsonObject = new JSONObject(jsonstring);
JSONArray profiles = jsonObject.getJSONArray("profiles");
for (int i = 0; i < profiles.length(); i++) {
JSONObject curProfile= (JSONObject) profiles.get(i);
JSONArray mails= (JSONArray)((JSONObject)curProfile.get("content")).get("mail");
System.out.println(mails.get(0));
}
}
}
as they have already said json standard doesn't impose ordering, so be careful
I can able to get mail by using below code
//root = my json
JsonObject rootobj = root.getAsJsonObject();
JsonArray profilesItems = rootobj.getAsJsonArray("profiles");
JsonObject firstValue = profilesItems.get(0).getAsJsonObject().getAsJsonObject("content");
JsonElement emails = firstValue.get("mail");
String mail = emails.getAsJsonArray().get(0).getAsString();
I am currently having trouble trying to parse this VCAP_SERVICES to java objects. I do not quite understand how to structure the POJO to allow it to map the values from the json string. Can someone please help me structure my pojo so that it is aligns with the json string?
I want to create objects for both of the credentials: accessToken... jdbcurl.
VCAP_SERVICES
"VCAP_SERVICES": {
"user-provided": [
{
"credentials": {
"accessTokenUri": "tokenurl",
"apiUrl": "apiurl",
"clientId": "typeofID",
"clientSecret": "secretAf",
"scope": "none"
},
"syslog_drain_url": "",
"volume_mounts": [],
"label": "user-provided",
"name": "OAuth2",
"tags": []
},
{
"credentials": {
"jdbcUrl": "jdbc:oracle:connection[host]:[port]/service",
"spring.datasource.driver-class-name": "oracle.jdbc.OracleDriver",
"spring.datasource.initialize": "false"
},
"syslog_drain_url": "",
"volume_mounts": [],
"label": "user-provided",
"name": "Database",
"tags": []
}
]
Java Class
ObjectMapper mapper = new ObjectMapper();
//json String to Object
CupsProperties properties = mapper.readValue(VCAP_Services, CupsProperties.class);
System.out.println(properties.getJdbcUrl() + "!!!!!!!!!!!!!!!!!!!");
POJOS
public class UserProviderWrapper {
#JsonProperty("user-provided")
public List<CupsProperties> cupsProperties;
#JsonProperty("syslog_drain_url")
public String syslog_drain_url;
#JsonProperty("volume_mounts")
public List<String> volume_mounts;
#JsonProperty("label")
public String label;
#JsonProperty("name")
public String name;
#JsonProperty("tags")
public List<String> tags;
//getters and setters
public class CupsProperties {
#JsonProperty("jdbcUrl")
public String jdbcUrl;
#JsonProperty("spring.datasource.driver-class-name")
public String driver;
#JsonProperty("spring.datasource.initialize")
public String initialize;
//getters and setters
Error
Unrecognized field "user-provided" (class rest.springframework.model.CupsProperties), not marked as ignorable (2 known properties: "jdbcUrl", "dataSource"])
at [Source: {"user-provided":[{ "credentials": { "jdbcUrl": "jdbc:oracle:thin:user/pass//host:port/service", "spring.datasource.driver-class-name": "oracle.jdbc.OracleDriver", "spring.datasource.initialize": "false" }, "syslog_drain_url": "", "volume_mounts": [ ], "label": "user-provided", "name": "Oracle", "tags": [ ] }]}; line: 1, column: 19] (through reference chain: rest.springframework.model.CupsProperties["user-provided"])
Check below solution and see if it fulfills your need. You can build on to it if you need to parse more fields.
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonParser {
public static void main(String[] args) {
String VCAP_Services = "{\"userProvided\": [{\"credentials\": {\"accessTokenUri\": \"tokenurl\",\"apiUrl\": \"apiurl\",\"clientId\": \"typeofID\",\"clientSecret\": \"secretAf\",\"scope\": \"none\"},\"syslog_drain_url\": \"\",\"volume_mounts\": [],\"label\": \"user-provided\",\"name\": \"OAuth2\",\"tags\": []},{\"credentials\": {\"jdbcUrl\": \"jdbc:oracle:connection[host]:[port]/service\",\"spring.datasource.driver-class-name\": \"oracle.jdbc.OracleDriver\",\"spring.datasource.initialize\": \"false\"},\"syslog_drain_url\": \"\",\"volume_mounts\": [],\"label\": \"user-provided\",\"name\": \"Database\",\"tags\": [] } ] } ";
CupsProperties properties=null;
try {
JSONParser jsonParser = new JSONParser();
JSONObject vcapServiceJSONObject = (JSONObject) jsonParser.parse(VCAP_Services);
for(Object key: vcapServiceJSONObject.keySet()){
String keyStr = (String) key;
JSONArray userProvidedList = (JSONArray) vcapServiceJSONObject.get(keyStr);
Iterator i = userProvidedList.iterator();
while (i.hasNext()) {
JSONObject innerObj = (JSONObject) i.next();
JSONObject credentialsObject = (JSONObject) innerObj.get("credentials");
if(credentialsObject.containsKey("jdbcUrl")){
//set to your pojo objects
System.out.println("JDBC url:" + credentialsObject.get("jdbcUrl"));
}
if(credentialsObject.containsKey("accessTokenUri")){
//set to your pojo objects
System.out.println("Access token URI:" + credentialsObject.get("accessTokenUri"));
}
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output
Access token URI:tokenurl
JDBC url:jdbc:oracle:connection[host]:[port]/service
I am trying to parse a JSON String and map it to a hashmap, I have a valid JSONString from server but when I traverse through it, all I can get it is the first result.
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList = new ArrayList<HashMap<String,String>>();
JSONObject jsonObj = new JSONObject(value);
Log.d("Jello",jsonObj.toString());
peoples = jsonObj.getJSONArray("product");//check here
Log.d("Jello",peoples.toString());
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("service_group",service_group);
persons.put("service",service);
persons.put("value",value);
persons.put("updated_at",updated_at);
personList.add(persons);
}
My JSON String is :
{"product":[{"sgroup":"Dummy_BIG_ONE","service":"Dummy_UNDER_BIG_ONE","code":"128","value":"0","updated_at":"2015-12-04 21:21:00"}]}{"product":[{"sgroup":"Hello Monkey","service":"Do u work","code":"123","value":"0","updated_at":"2015-12-04 21:27:51"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:39"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:40"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:42"}]}{"product":[{"sgroup":"Hello World","service":"Donkey","code":"24411","value":"0","updated_at":"2015-12-04 22:57:05"}]}{"product":[{"sgroup":"lkfnhjdiofho","service":"dfjdifj","code":"1101","value":"0","updated_at":"2015-12-05 01:15:49"}]}{"product":[{"sgroup":"Baal","service":"Saal","code":"1234","value":"21","updated_at":"2015-12-05 01:34:59"}]}{"product":[{"sgroup":"Inis","service":"Mona","code":"1234","value":"1001","updated_at":"2015-12-05 01:39:51"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"0","updated_at":"2015-12-05 01:50:42"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"0","updated_at":"2015-12-05 01:55:12"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"1000","updated_at":"2015-12-05 01:56:10"}]}
or HERE
here is how I am sending the JSON
while($row = mysql_fetch_assoc($output))
{
$product = array();
$product["sgroup"] = $row["service_group"];
$product["service"] = $row["service"];
$product["code"] = $row["code"];
$product["value"] = $row["amount"];
$product["updated_at"] = $row["updated_at"];
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
}
I want to add all the data's from the JSON in my ArrayList so that I can use it later.
Thank you for your help.
First, there are online tools available to determine if your JSON is valid.
Here is a general example of a better way to format your JSON data:
<?php
$bigArray = array();
for ($x = 0; $x <= 10; $x++) {
$product = array();
$product["sgroup"] = $x;
$product["service"] = $x;
$product["code"] = $x;
$product["value"] = $x;
$product["updated_at"] = $x;
array_push($bigArray, $product);
}
// echoing JSON response
echo json_encode($bigArray);
?>
Which gives this valid JSON response that is simple and easy to parse:
[
{
"sgroup":0,
"service":0,
"code":0,
"value":0,
"updated_at":0
},
{
"sgroup":1,
"service":1,
"code":1,
"value":1,
"updated_at":1
},
{
"sgroup":2,
"service":2,
"code":2,
"value":2,
"updated_at":2
},
{
"sgroup":3,
"service":3,
"code":3,
"value":3,
"updated_at":3
},
{
"sgroup":4,
"service":4,
"code":4,
"value":4,
"updated_at":4
},
{
"sgroup":5,
"service":5,
"code":5,
"value":5,
"updated_at":5
},
{
"sgroup":6,
"service":6,
"code":6,
"value":6,
"updated_at":6
},
{
"sgroup":7,
"service":7,
"code":7,
"value":7,
"updated_at":7
},
{
"sgroup":8,
"service":8,
"code":8,
"value":8,
"updated_at":8
},
{
"sgroup":9,
"service":9,
"code":9,
"value":9,
"updated_at":9
},
{
"sgroup":10,
"service":10,
"code":10,
"value":10,
"updated_at":10
}
]
As for the parsing, using a HashMap is not the best way. Create a list of Person POJO objects.
First define the Person class:
class Person {
public String group;
public String service;
public String value;
public String updated;
public Person(String g, String s, String v, String u) {
group = g;
service = s;
value = v;
updated = u;
}
}
Then, parsing is fairly simple:
List<Person> personList = new ArrayList<>();
JSONArray jsonArr;
try {
jsonArr = new JSONArray(response);
for(int i=0;i<jsonArr.length();i++){
JSONObject c = jsonArr.getJSONObject(i);
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
Person p = new Person(service_group, service, value, updated_at);
personList.add(p);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You should put your products into json array:
[
{
"product": {
"sgroup": "lkfnhjdiofho",
"service": "dfjdifj",
"code": "1101",
"value": "0",
"updated_at": "2015-12-05 01:15:49"
}
},
{
"product": {
"sgroup": "Baal",
"service": "Saal",
"code": "1234",
"value": "21",
"updated_at": "2015-12-05 01:34:59"
}
},
{
"product": {
"sgroup": "Inis",
"service": "Mona",
"code": "1234",
"value": "1001",
"updated_at": "2015-12-05 01:39:51"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "0",
"updated_at": "2015-12-05 01:50:42"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "0",
"updated_at": "2015-12-05 01:55:12"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "1000",
"updated_at": "2015-12-05 01:56:10"
}
}
]
And you have to change your parser little bit:
JSONArray jsonArray = new JSONArray(string);
for(int i=0;i<jsonArray.length();i++){
JSONObject c = jsonArray.getJSONObject(i).getJSONObject("product");
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("service_group",service_group);
persons.put("service",service);
persons.put("value",value);
persons.put("updated_at",updated_at);
personList.add(persons);
}
You don't need put your object into "product" attribute, but directly into array :
[
{
"sgroup": "lkfnhjdiofho",
"service": "dfjdifj",
"code": "1101",
"value": "0",
"updated_at": "2015-12-05 01:15:49"
},
{
"sgroup": "Baal",
"service": "Saal",
"code": "1234",
"value": "21",
"updated_at": "2015-12-05 01:34:59"
},
I'm trying to build a JSON object in my servlet.
The object should look like this:
{
"firms": [
{
"name": "firm1",
"projects": [
{
"name": "firm1project1"
},
{
"name": "firm1project2"
},
{
"name": "firm1project3"
}
]
},
{
"name": "firm2",
"projects": [
{
"name": "firm2project1"
},
{
"name": "firm2project2"
},
{
"name": "firm2project3"
}
]
},
{
"name": "firm3",
"projects": [
{
"name": "firm3project1"
},
{
"name": "firm3project2"
},
{
"name": "firm3project3"
}
]
},
{
"name": "firm4",
"projects": [
{
"name": "firm4project1"
},
{
"name": "firm4project2"
},
{
"name": "firm4project3"
}
]
}
]
}
I have a problem in creating array of project names objects:
[
{
"name": "firm2project1"
},
{
"name": "firm2project2"
},
{
"name": "firm2project3"
}
]
Right now I have the code as showed below (oJsonInner is a JSONObject object, aProjects - ArrayList of JSONObject type). I build the oJsonInner object from the results I get from database query:
while(result.next()){
oJsonInner.put("name",result.getString("project_name"));
aProjects.add(oJsonInner);
}
Is there any way to get the value of the oJsonInner object in aProjects.add(oJsonInner); so during the next loop I could create a new oJsonInner object with different "project_name" value without updating the object that got into aProjects array during the first loop?
while(result.next()){
oJsonInner = new JsonObject();
oJsonInner.put("name",result.getString("project_name"));
aProjects.add(oJsonInner);
}
you can use a JSONArray object and add it JSON object.
while(result.next()){
JSONObject oJsonInner = new JSONObject();
JSONArray arr = new JSONArray();
json.put("name",result.getString("project_name"));
arr.put(json);
}
Try this method:
ArrayList<JSONObject> aProjects = new <JSONObject>ArrayList();
while(result.next()){
JSONObject oJsonInner = new JSONObject();
oJsonInner.put("name","project1");
aProjects.add(oJsonInner);
}
RESULT:
[{"name":"project1"}, {"name":"project2"}]
Use Gson lib that help you to serialize json format which take java bean and convert it to json format.
Model
public class Firm {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private List<Project> projetcts;
public List<Project> getProjetcts() {
return projetcts;
}
public void setProjetcts(List<Project> projetcts) {
this.projetcts = projetcts;
}
public static class Project{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
Gson code
public static void main(String[] args) {
Firm [] firms = new Firm[2];
Project p1 = new Project();
p1.setName("project 1");
Project p2 = new Project();
p2.setName("project 2");
Project p3 = new Project();
p3.setName("project 3");
List<Project> projects = new ArrayList<Firm.Project>();
projects.add(p1);
projects.add(p2);
projects.add(p3);
Firm firm1 = new Firm();
firm1.setName("firm1");
firm1.setProjetcts(projects);
Firm firm2 = new Firm();
firm2.setName("firm2");
firm2.setProjetcts(projects);
firms[0] = firm1;
firms[1] = firm2;
String jsonText = new Gson().toJson(firms);
System.out.println(jsonText);
}
Result Sample
[{"name":"firm1","projetcts":[{"name":"project 1"},{"name":"project
2"},{"name":"project
3"}]},{"name":"firm2","projetcts":[{"name":"project
1"},{"name":"project 2"},{"name":"project 3"}]}]
Check this solution, it may satisfy your expectations:
https://stackoverflow.com/a/74174150/2609399
UPDATE:
In your case, the needed JSON object can be created like so (note that actual key-value lines can be imported from external files or other sources like socked, db and so on):
System.out.println(
JsonBuilder.of()
.add("[0].name", "firm2project1")
.add("[1].name = firm2project2")
.add("[2].name: \"firm2project3\"")
.build()
.toPrettyString()
);
, which results to:
[
{
"name": "firm2project1"
},
{
"name": "firm2project2"
},
{
"name": "firm2project3"
}
]
I am trying to deserialize the following string, I am somewhat new to java and I cannot get this to work for the life of me... I am only trying to decode two strings in the object for now. My JSON and Java classes below. I am getting the result variable ok.
{
"result": "true",
"recentlyMarkedTerritories": {
"0": {
"pk_activity": "471",
"fk_activity_type": "100",
"activity_content": "Hhhhh",
"fk_user": "2",
"activity_image": "2_QZe73f4t8s3R1317230457.jpg",
"created": "1317244857",
"activity_status": "1",
"activity_location_lat": "43.515283",
"activity_location_lon": "-79.880678",
"fk_walk": null,
"fk_event_location": "73",
"user_point": "0",
"public_image": "0",
"fk_event_location_lat": "43.515273",
"fk_event_location_lon": "-79.879989",
"profile_image": "2_y9JlkI3CZDml1312492743.jpg",
"user_gender": "1",
"user_dob": "236073600",
"user_nickname": "junoman",
"isFriend": "false",
"profile_image_thumb": "2_y9JlkI3CZDml1312492743_t.jpg",
"activity_image_thumb": "2_QZe73f4t8s3R1317230457_t.jpg",
"relationship_status_idx": "2",
"isBlocked": "false"
},
"1": {
"pk_activity": "469",
"fk_activity_type": "100",
"activity_content": "Jsjsjs",
"fk_user": "1",
"activity_image": null,
"created": "1317244508",
"activity_status": "1",
"activity_location_lat": "43.515283",
"activity_location_lon": "-79.880678",
"fk_walk": null,
"fk_event_location": "73",
"user_point": "0",
"public_image": "0",
"fk_event_location_lat": "43.515273",
"fk_event_location_lon": "-79.879989",
"profile_image": "1_4Cpkofueqnrb1316895161.jpg",
"user_gender": "1",
"user_dob": "116841600",
"user_nickname": "JoePennington",
"isFriend": "false",
"profile_image_thumb": "1_4Cpkofueqnrb1316895161_t.jpg",
"activity_image_thumb": null,
"relationship_status_idx": "1",
"isBlocked": "false"
},
.....
}
}
And my java class below
RecentActivity infoList = null;
Gson gson = new Gson();
infoList = gson.fromJson(JSONString, RecentActivity.class);
public class RecentActivity {
String result;
recentlyMarkedTerritories recentlyMarkedTerritories = null;
public RecentActivity() {
}
public class recentlyMarkedTerritories {
public Set<recentlyMarkedTerritories> pk_activity = new HashSet<recentlyMarkedTerritories>() ;
public recentlyMarkedTerritories() { }
}
}
Please forgive my lack of description but I'm sure the code helps. The JSON is already used in other applications so changing it is not an option.. :(
Thanks!
Here are some nice Tutorials for JSON that will help you out.
GSON
JSON
JSON Example with source code
UPDATED
Try like this,
try {
JSONObject object = new JSONObject(jsonString);
JSONObject myObject = object.getJSONObject("recentlyMarkedTerritories");
for (int i = 0; i < object.length(); i++) {
JSONObject myObject2 = myObject.getJSONObject(Integer.toString(i));
System.out.println(myObject2.toString(2));
}
} catch (Exception e) {
e.printStackTrace();
}
I am not sure of the gson code to write, but the structure of your json looks more like the following java representation (though you might want booleans and ints instead of String fields):
public class RecentActivity {
String result;
Map<String,RecentlyMarkedTerritory> recentlyMarkedTerritories = null;
}
public class RecentlyMarkedTerritory {
String pk_activity;
// other fields
}