JSON:
{
"prop":"property",
"inputInfo":{
"sku":"6157068",
"inputText":"iphone"
}
}
Code:
JSONObject inputObject = JSON.parseObject(input);
String prop = (String)inputObject.get("property");
But how to get the inner layer of 'sku' & 'inputText'?
I am using Alibaba json library in Java.
I haven't used the Alibaba library but doesn't it have a getJSONObject() method that you can use on inputObject? I have done this before but I used org.json library.
JSON:
{"circle":{
"radius":255819.07998349078,
"center":{
"lat":00.000000000000000,
"lng":00.000000000000000
}
}
}
Java
JSONObject shape = new JSONObject(entity.getJsonLocation());
double latitude = shape.getJSONObject("circle")
.getJSONObject("center")
.getDouble("lat");
double longitude = shape.getJSONObject("circle")
.getJSONObject("center")
.getDouble("lng");
This example for instance gets the JSON and creates a JSONObject shape. I can then get the inner json objects by calling getJSONObject() on shape.
I hope this can help you.
You can create a bean at first, for instance,
public class DemoInfo {
private String id;
private String city;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setCity(String city) {
this.city = city;
}
public String getCity() {
return city;
}
}
then,
String s = "{\"id\":\"0375\",\"city\":\"New York\"}";
DemoInfo info = JSON.parseObject(s, DemoInfo.class);
or you can use map instead.
JSON.parseObject(s, HashMap.class);
You can do it like this,
JSONObject inputInfoObject = inputObject.getJSONObject("inputInfo");
String sku = inputInfoObject.getString("sku");
String inputText = inputInfoObject.getString("inputText");
If you can use GSON the following is possible
public static void main(String[] args) throws IOException {
String json = "{\"prop\":\"property\",\"inputInfo\":{\"sku\":\"6157068\",\"inputText\":\"iphone\"}}";
Gson gson = new Gson();
HashMap<String, Object> res = gson.fromJson(json, HashMap.class);
for (Map.Entry<String, Object> entry : res.entrySet()) {
if ("inputInfo".equalsIgnoreCase(entry.getKey())) {
HashMap<String, Object> map = gson.fromJson(String.valueOf(entry.getValue()), HashMap.class);
for (Map.Entry<String, Object> child : map.entrySet()) {
System.out.println(child.getKey() + " : " + child.getValue());
}
}
}
}
And the result is
inputText : iphone
sku : 6157068.0
Related
I can not convert Java object to JSON object this is my main java object :
I do this:
public class LoginDao {
String company;
String user;
String secure_password;
String secure_device_id;
app_info app_info;
}
jsonObject.put("company", company);
jsonObject.put("user", user);
jsonObject.put("os", os);
jsonObject.put("ver", ver);
jsonObject.put("lang", lang);
but on output I do not have this :
{
"company":"",
"user":"test",
"secure_password":"",
"secure_device_id":"",
"app_info":
{
"os":"soapui",
"ver":1,
"lang":"pl"
}
}
You can do this in many more way. Here are given bellow:
Using Google Gson:
Maven dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
Java code:
LoginDao loginData;
// Here loginData is the object. ...
Gson gson = new Gson();
String json = gson.toJson(loginData);
Using Jackson:
Gradle Dependency:
compile 'com.fasterxml.jackson.core:jackson-databind:2.5.3'
Java code
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(loginData);
If you need above output, try this:
JSONObject obj = new JSONObject();
obj.put("company", company);
obj.put("user", user);
obj.put("secure_password", secure_password);
obj.put("secure_device_id", secure_device_id);
JSONObject anothetObj = new JSONObject();
anothetObj.put("os", os);
anothetObj.put("ver", ver);
anothetObj.put("lang", lang);
obj.put("app_info", anothetObj);
You can create two DAO Classes,
public class LoginDAO {
private String company;
private String user;
private String secure_password;
private String secure_device_id;
// Getter Methods
public String getCompany() {
return company;
}
public String getUser() {
return user;
}
public String getSecure_password() {
return secure_password;
}
public String getSecure_device_id() {
return secure_device_id;
}
// Setter Methods
public void setCompany( String company ) {
this.company = company;
}
public void setUser( String user ) {
this.user = user;
}
public void setSecure_password( String secure_password ) {
this.secure_password = secure_password;
}
public void setSecure_device_id( String secure_device_id ) {
this.secure_device_id = secure_device_id;
}
}
public class App_info {
private String os;
private float ver;
private String lang;
// Getter Methods
public String getOs() {
return os;
}
public float getVer() {
return ver;
}
public String getLang() {
return lang;
}
// Setter Methods
public void setOs( String os ) {
this.os = os;
}
public void setVer( float ver ) {
this.ver = ver;
}
public void setLang( String lang ) {
this.lang = lang;
}
}
An then you can do this,
LoginDAO login = new LoginDAO();
App_info app = new App_info();
JSONObject jo = new JSONObject();
jo.put("company", login.getCompany());
jo.put("user", login.getUser());
jo.put("secure_password", login.getSecure_password());
jo.put("secure_device_id", login.getSecure_device_id());
Map m = new LinkedHashMap(3);
m.put("os", app.getOs());
m.put("ver", app.getVer());
m.put("lang", app.getLang());
jo.put("app_info", m);
System.out.println(jo.toString);
If not you can simply do this,
JSONObject jo = new JSONObject(
"{ \"company\":\"\", \"user\":\"test\", \"secure_password\":\"\", \"secure_device_id\":\"\", \"app_info\": { \"os\":\"soapui\", \"ver\":1, \"lang\":\"pl\" } }"
);
I'm using Android Studio and I want to make a listview, which contains values that are received by JSON.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String JSONString = Handler.makeServiceCall(JSONUrl);
Log.e(TAG, "Response:" + JSONString);
if(JSONString != null){
try {
JSONObject CountriesJSONObject = new JSONObject(JSONString);
JSONArray Countries = CountriesJSONObject.getJSONArray("countries");
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i);
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
} catch (final JSONException e){
Log.e(TAG,e.getMessage());
ProgressDialog.setMessage("Error loading Data!");
}
}
return null;
}
This is the code for getting the JSON values, and i'm receiving an error
"No value for id"
What am I doing wrong?
You still have the "country" key to unwrap. Try like this:
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i).getJSONObject("country");
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
First step is to create a new Java class model for the JSON - you can just copy and paste this.
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
public class Countries {
public class CountriesList implements Serializable {
private Country[] countries;
public Country[] getCountries() {
return countries;
}
public void setCountries(Country[] countries) {
this.countries = countries;
}
public ArrayList<Country> getCountriesAsList() {
if(countries == null || countries.length == 0) {
return new ArrayList<>();
} else {
return (ArrayList<Country>) Arrays.asList(countries);
}
}
}
public class Country implements Serializable {
private String id;
private String name;
private String image;
public Country() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
}
Now, it's simply converting the JSON into Java object like this. You can use that ArrayList for adapter or however you like.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String jsonString = Handler.makeServiceCall(JSONUrl);
Countries.CountriesList countries = new Gson().fromJson(jsonString, Countries.CountriesList.class);
// this is the full list of all your countries form json
ArrayList<Countries.Country> countryList = countries.getCountriesAsList();
}
Note: you will need the Gson library to use the solution I showed above. I use that to convert JSON into Java object.
compile 'com.google.code.gson:gson:2.8.0'
I have hashmap string object below. How to get value name from object SubSource.value index 0? I just found function for get first object, for example I just get value from test with hashMapValue.get("test"). How to get value object inside the object? should I convert to json and I get the value? Thanks.
{
"test" : {
"type" : "",
"value" : ""
},
"Attachment" : {
"type" : "",
"value" : ""
},
"SubSource" : {
"type" : "string",
"value" : [ {
"address" : "xxx.xxxx#xxx.co.id",
"name" : "bobby"
}, {
"address" : "xxx.xxxx#xxx.co.id",
"name" : "2sadasd"
}, {
"address" : "xxx.xxxx#xxx.co.id",
"name" : "ggfgf"
} ]
}
}
My code:
Map<String, Object> departmentPHSSuportEmail = new HashMap<String, Object>();
Map<String, Object> subSourceMap = null;
List<Map<String , Object>> myMap = new ArrayList<Map<String,Object>>();
Map<String, Object> attachment = new HashMap<String, Object>();
attachment.put("type", "");
attachment.put("value", "");
departmentPHSSuportEmail.put("Attachment", attachment);
Map<String, Object> subSource = new HashMap<String, Object>();
subSource.put("type", "string");
subSource.put("value", myMap);
departmentPHSSuportEmail.put("SubSource", subSource);
// create a fresh map
Map<String,Object> subSourceMap1 = new HashMap<>();
subSourceMap1.put("name", "bobby");
subSourceMap1.put("address", "xxx.xxxx#xxx.co.id");
// create a fresh map
Map<String,Object> subSourceMap2 = new HashMap<>();
subSourceMap2.put("name", "2sadasd");
subSourceMap2.put("address", "xxx.xxxx#xxx.co.id");
// create a fresh map
Map<String,Object> subSourceMap3 = new HashMap<>();
subSourceMap3.put("name", "ggfgf");
subSourceMap3.put("address", "xxx.xxxx#xxx.co.id");
myMap.add(subSourceMap1);
myMap.add(subSourceMap2);
myMap.add(subSourceMap3);
Map<String, Object> attachments = new HashMap<String, Object>();
attachments.put("type", "");
attachments.put("value", "dasda");
departmentPHSSuportEmail.put("test", attachments);
Not sure what you are asking, but...
A) Cast the object you are getting from the map to the Object type you are trying to grab the values out of
String name = (String) subSourceMap1.get("name");
B) Add type parameters to your map
Map<String, String> subSourceMap1 = new HashMap<String, String>();
String name = subSourceMap1.get("name");
String address = subSourceMap1.get("address");
C) If you are wondering how to get those maps out of a list
Map<String, YourObject> subSourceMap1 = myMap.get(0); //This is index 0's of your map subsource
//You can grab index's from 'myMap' that are less than myMap.size();
This is a JSON string. Find a proper JSON deserializer library and include that in your project instead of coding all this HashMap stuff.. ;)
Ie this
jackson-2-convert-object-to-from-json
Map<String, Object> subSource2 = (Map<String, Object>)departmentPHSSuportEmail.get("SubSource");
List<Map<String , Object>> myMap2 = (List<Map<String , Object>>)subSource2.get("value");
Map<String,Object> subSourceMap3 = myMap2.get(0);
String value = (String)subSourceMap3.get("value");
There are many ways how to solve this, one of solutions can be like this:
make container for member data (address + name), if the addresses
should be unique, than can be used as a key in map
make container for attachment
make container for the whole data, because of data integrity
Please, notice, I have used hashmap for members, but arraylist for attachments, if you are expecting also unique values at attachments, than you can use also hashmap with key name, then you can use it for finding
So..
Member container
public class Member {
private String name;
private String address;
public Member(String name, String address) {
super();
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
Container for attachments
public class Attachment {
String name;
String value;
public Attachment(String name, String value) {
super();
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Than container for complete data
public class DataContainer {
Map<String, Member> membersMap;
ArrayList<Attachment> attachments;
public DataContainer() {
this.membersMap = new HashMap<String, Member>();
this.attachments = new ArrayList<Attachment>();
}
public DataContainer(Map<String, Member> membersMap, ArrayList<Attachment> attachments) {
super();
this.membersMap = membersMap;
this.attachments = attachments;
}
public Map<String, Member> getMembersMap() {
return membersMap;
}
public void setMembersMap(Map<String, Member> membersMap) {
this.membersMap = membersMap;
}
public ArrayList<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(ArrayList<Attachment> attachments) {
this.attachments = attachments;
}
public void addAttachment(Attachment newItem) {
this.attachments.add(newItem);
}
public void addMember(Member newMember) {
this.membersMap.put(newMember.getAddress(), newMember);
}
public Member getMemberByAddress(String address) {
return this.membersMap.get(address);
}
}
Filling example
Map<String, Member> membersMap= new HashMap<String, Member>();
Member newMember = new Member("fooo Name", "fooo#whatever.foo");
membersMap.put(newMember.getAddress(), newMember);
Attachment newAtatchment = new Attachment("fooattach", "something");
ArrayList<Attachment> attachments = new ArrayList<>();
attachments.add(newAtatchment);
DataContainer data = new DataContainer(membersMap, attachments);
data.addMember(new Member("anotherMember", "fooo#foooo.foo"));
data.addAttachment(new Attachment("another attachmetn", "anotherAtt value"));
I have several classes like this. I want to convert the classes into JSONObject format.
import java.io.Serializable;
import com.google.gson.annotations.SerializedName;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#SerializedName("id")
private Integer mId;
#SerializedName("name")
private String mName = "";
#SerializedName("email")
private String mEmail;
public Integer getId() {
return mId;
}
public void setId(Integer id) {
mId = id;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getEmail() {
return mEmail;
}
public void setEmail(String email) {
mEmail = email;
}
}
I know that I can convert these classes to JSONObject format as follows:
User user = new User();
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("id", user.getId());
jsonObj.put("name", user.getName());
jsonObj.put("email", user.getEmail());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The problem is that I need to do this for a lot of different classes that are much longer than this across a lot of files. Can I use GSON to fill the JSONObject from myClass so that I don't need to edit every time the class structure changes?
The following returns a JSON string but I need it as an Object as when I send it to the system that sends the requests via a REST API it sends with unwanted quotation marks.
User user = new User();
Gson gson = new Gson();
Object request = gson.toJson(user);
When I use this in another JSON builder that asks for an Object I get
{"request":"{"id":"100","name":"Test Name","email":"test#example.com"}"}
When I want
{"request":{"id":"100","name":"Test Name","email":"test#example.com"}}
I found that the following works with GSON:
User = new User();
Gson gson = new Gson();
String jsonString = gson.toJson(user);
try {
JSONObject request = new JSONObject(jsonString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is not type safe, however.
Here is a crude example you can use to use Reflection to build the JSONObject..
Warning it's not pretty and does not contain really type-safety.
public static JSONObject quickParse(Object obj) throws IllegalArgumentException, IllegalAccessException, JSONException{
JSONObject object = new JSONObject();
Class<?> objClass = obj.getClass();
Field[] fields = objClass.getDeclaredFields();
for(Field field : fields) {
field.setAccessible(true);
Annotation[] annotations = field.getDeclaredAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof SerializedName){
SerializedName myAnnotation = (SerializedName) annotation;
String name = myAnnotation.value();
Object value = field.get(obj);
if(value == null)
value = new String("");
object.put(name, value);
}
}
}
return object;
}
Here is an example usage:
User user = new User();
JSONObject obj = quickParse(user);
System.out.println(obj.toString(3));
Output
{
"id": "",
"name": "",
"email": ""
}
Try with this code:
// Returns the JSON in a String
public String getJSON()
{
Gson gson = new Gson();
return gson.toJson(this);
}
// Builds the Model Object from the JSON String
MyModel model =new MyModel();
JSONObject j = new JSONObject(model.getJSON());
I am implementing a REST API which send and receive data with json(I am totally new to this API design). I am using Spring framework and requestbody/responsebody for mapping.
Initially, I had a pojo like this:
public class Action implements Serializable {
#Id
private String id;
private String name;
private String applicationId;
private String timeStamp;
private String username;
private String options;
//Getters and Setters
}
and the json format for this pojo is like this:
{
"id": "11954cd5-eec3-4f68-b0e8-a4d9b6a976a9",
"name": "kill button",
"applicationId": "34fa7bbf-e49f-4f2a-933a-de26b9fdb0f1",
"timeStamp": "2014-03-05T11:51+0000",
"username": "user1783",
"options": "facebook app"
}
This is how the controller look like:I do not get any json, Spring is converting already to java object, should it do it manually myself?
#RequestMapping(value = "applications/{appId}/actions", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
#ResponseBody
public Action addAction(#PathVariable String appId, #RequestBody Action action) {
return actionService.add(appId, action);
}
you can find a pretty json format of it here:
https://gist.github.com/bakharzy/8948950
I want to change the last pair in the json to be a json itself as it is shown in the second json format in gist. So user can send more information. Now that I have a new format for json which is kind of json in json, how should I change the pojo (private String options;) to store the data coming from second json format. Note that the inner json can have arbitrary number of pairs.
My first idea is to change the options in pojo to something like Hash object. Is it doable? If so, how?
Thanks
Just use a nested Object like so:
public class Action implements Serializable {
#Id
private String id;
private String name;
private String applicationId;
private String timeStamp;
private String username;
private Map<String, String> options;
//Getters and Setters
}
This will give you this format:
{
"id": "11954cd5-eec3-4f68-b0e8-a4d9b6a976a9",
"name": "kill button",
"applicationId": "34fa7bbf-e49f-4f2a-933a-de26b9fdb0f1",
"timeStamp": "2014-03-05T11:51+0000",
"username": "user1783",
"options":{
"data": "Click Here",
"size": "36",
"application":"facebook app"
}
}
UPDATE: - Adding test to prove that the solution does indeed work.
public class ActionTest {
#Test
public void testObjectToJson() throws JsonProcessingException {
Action action = new Action();
action.setId("id");
action.setUsername("username");
action.setApplicationId("applicationId");
action.setName("name");
action.setTimeStamp("timestamp");
Map<String, String> map = Maps.newHashMap();
map.put("key", "value");
map.put("key2", "value2");
action.setOptions(map);
ObjectMapper mapper = new ObjectMapper();
String value = mapper.writeValueAsString(action);
System.out.println(value);
}
#Test
public void testJsonToObject() throws IOException {
String json = "{\"id\":\"id\",\"name\":\"name\",\"applicationId\":\"applicationId\",\"timeStamp\":\"timestamp\",\"username\":\"username\",\"options\":{\"key\":\"value\", \"key2\":\"value2\"}}";
ObjectMapper mapper = new ObjectMapper();
Action value = mapper.readValue(json, Action.class);
System.out.println(value);
}
}
class Action {
private String id;
private String name;
private String applicationId;
private String timeStamp;
private String username;
private Map<String, String> options;
public Action() {}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("Action{");
sb.append("id='").append(id).append('\'');
sb.append(", name='").append(name).append('\'');
sb.append(", applicationId='").append(applicationId).append('\'');
sb.append(", timeStamp='").append(timeStamp).append('\'');
sb.append(", username='").append(username).append('\'');
sb.append(", options=").append(options);
sb.append('}');
return sb.toString();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Map<String, String> getOptions() {
return options;
}
public void setOptions(Map<String, String> options) {
this.options = options;
}
}
Map<String, Object> innerMap = new WhateverMap<String, Object>();
innerMap.put("data", "click here");
innerMap.put("size", "36");
innerMap.put("application", "facebook app");
Map<String, Object> outerMap = new WhateverMap<String, Object>();
outerMap.put("name", "kill button");
outerMap.put("username", "user1783");
outerMap.put("options", innerMap);
String jsonString = jsonEncoder.encode(outerMap);