I am trying to use Jackson to parse sample json as demonstrated below. However, I the parsing doesn't work (fails without any exceptions - as I get an empty string for event.getAccountId(); What could I be doing wrong?
Thanks!
ObjectMapper om = new ObjectMapper();
String json = "{\"_procurementEvent\" : [{ \"accountId\" : \"3243234\",\"procurementType\" : \"view\"," +
"\"_procurementSubType\" : \"Standard Connector\",\"_quantity\" : \"4\", \"_pricePerMonth\" : \"100.00\"" +
",\"_annualPrice\" : \"1200.00\"}]}";
ProcurementEvent event = om.readValue(json, ProcurementEvent.class);
event.getAccountId(); // returns null
#JsonIgnoreProperties(ignoreUnknown = true)
private static class ProcurementEvent {
private String _accountId;
private String _procurementType;
private String _quantity;
private String _pricePerMonth;
private String _annualPrice;
#JsonProperty("accountId")
public String getAccountId() {
return _accountId;
}
public void setAccountId(String accountId) {
_accountId = accountId;
}
#JsonProperty("procurementType")
public String getProcurementType() {
return _procurementType;
}
public void setProcurementType(String procurementType) {
_procurementType = procurementType;
}
#JsonProperty("_quantity")
public String getQuantity() {
return _quantity;
}
public void setQuantity(String quantity) {
_quantity = quantity;
}
#JsonProperty("_pricePerMonth")
public String getPricePerMonth() {
return _pricePerMonth;
}
public void setPricePerMonth(String pricePerMonth) {
_pricePerMonth = pricePerMonth;
}
#JsonProperty("_annualPrice")
public String getAnnualPrice() {
return _annualPrice;
}
public void setAnnualPrice(String annualPrice) {
_annualPrice = annualPrice;
}
}
In the question, try the following approach:
class ProcurementEvents {
private List<ProcurementEvent> _procurementEvent; // + annotations like #JsonIgnoreProperties, getters/ setters, etc.
}
// json from your example
ProcurementEvents events = om.readValue(json, ProcurementEvents.class);
events.get(0).getAccountId();
Related
I have the below json which im serializing
{
"name":"John",
"switch":"1"
},
{
"name":"Jim",
"switch":"0"
}
I want to serialize it to a differnt name So I had to do it like below
class Data {
private String name;
private String flag;
#JsonProperty("flag")
public byte getFlag() {
return flag;
}
#JsonProperty("switch")
public void setSwitch(String s) {
this.flag = flag;
}
}
So that I get it converted as below
{
"name":"John",
"flag":"1"
},
{
"name":"Jim",
"flag":"0"
}
Now I wanted to map the numic values to Y and N for 1 and 0 respectively. Can I acheive that ?
Im expecting my final string to be like this
{
"name":"John",
"switch":"Y"
},
{
"name":"Jim",
"switch":"N"
}
I agree with #Gaƫl J, but still if you want to go ahead this code change might help you to convert that 1/0 to Y/N.
public class Application {
#ToString
static class Input {
#JsonProperty("name")
private String name;
#JsonProperty("switch")
private String flag;
#JsonProperty("name")
public void setName(String name){
this.name = name;
}
#JsonProperty("switch")
public void setSwitch(String s) {
for(SwitchMap valuePair : SwitchMap.values()){
if(valuePair.getValue().equals(s)){
this.flag = valuePair.name();
}
}
}
}
public static void main(String[] args) throws JsonProcessingException {
String json = "{\n" +
"\"name\":\"John\",\n" +
"\"switch\":\"1\"\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
Input in = mapper.readValue(json, Input.class);
System.out.println(mapper.writeValueAsString(in));
}
}
define an enum with the mapping
#Getter
public enum SwitchMap {
Y("1"),
N("0");
private final String value;
private SwitchMap(String value){
this.value = value;
}
}
I'm using retrofit2 and Rxjava2 to insert/get information from mongodb and nodeJs server, for now, I receive all data as a string but I want to get hole collection Infos from my base so I need to convert string to JSON and get each information.
My code to receive data:
1- Service:
#POST("collect/get")
#FormUrlEncoded
Observable<String> getcollection(#Field("selector") String selector);
2-RetrofitClient:
if(instance == null){
instance = new Retrofit.Builder()
.baseUrl("http://transportor.ddns.net:3000/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create()).build();
}
3- Recieve function
private void getallcollection(String selector) {
compositeDisposable.add(myServices.getcollection(selector)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<String>(){
#Override
public void accept(String s) throws Exception {
Log.d("infos",s);
}
}));
}
I'm already prepared Collection class:
public class col {
private String creator;
private String emailcol;
private String date_creation_col;
private String nom_col;
private String long_col;
private String lat_col;
private String tel_fix_col;
private String tel_mobile_col;
private String creatorcreator;
private String heure_matin_col;
private String heure_apresmatin_col;
private String type;
private String imagePath;
public col(String creator, String emailcol, String date_creation_col, String nom_col, String long_col, String lat_col, String tel_fix_col, String tel_mobile_col, String creatorcreator, String heure_matin_col, String heure_apresmatin_col, String type, String imagePath) {
this.creator = creator;
this.emailcol = emailcol;
this.date_creation_col = date_creation_col;
this.nom_col = nom_col;
this.long_col = long_col;
this.lat_col = lat_col;
this.tel_fix_col = tel_fix_col;
this.tel_mobile_col = tel_mobile_col;
this.creatorcreator = creatorcreator;
this.heure_matin_col = heure_matin_col;
this.heure_apresmatin_col = heure_apresmatin_col;
this.type = type;
this.imagePath = imagePath;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getEmailcol() {
return emailcol;
}
public void setEmailcol(String emailcol) {
this.emailcol = emailcol;
}
public String getDate_creation_col() {
return date_creation_col;
}
public void setDate_creation_col(String date_creation_col) {
this.date_creation_col = date_creation_col;
}
public String getNom_col() {
return nom_col;
}
public void setNom_col(String nom_col) {
this.nom_col = nom_col;
}
public String getLong_col() {
return long_col;
}
public void setLong_col(String long_col) {
this.long_col = long_col;
}
public String getLat_col() {
return lat_col;
}
public void setLat_col(String lat_col) {
this.lat_col = lat_col;
}
public String getTel_fix_col() {
return tel_fix_col;
}
public void setTel_fix_col(String tel_fix_col) {
this.tel_fix_col = tel_fix_col;
}
public String getTel_mobile_col() {
return tel_mobile_col;
}
public void setTel_mobile_col(String tel_mobile_col) {
this.tel_mobile_col = tel_mobile_col;
}
public String getCreatorcreator() {
return creatorcreator;
}
public void setCreatorcreator(String creatorcreator) {
this.creatorcreator = creatorcreator;
}
public String getHeure_matin_col() {
return heure_matin_col;
}
public void setHeure_matin_col(String heure_matin_col) {
this.heure_matin_col = heure_matin_col;
}
public String getHeure_apresmatin_col() {
return heure_apresmatin_col;
}
public void setHeure_apresmatin_col(String heure_apresmatin_col) {
this.heure_apresmatin_col = heure_apresmatin_col;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
Actually I received all data and console show me : [{"_id":"5e22074673c926147c3a73f5","date_creation_col":"17-01-2020","creator":"Alaeddine","emailcol":"amir#gmail.com","nom_col":"amir","long_col":"10.179326869547367","lat_col":"36.83353893150942","tel_fix_col":"123","tel_mobile_col":"1234","adress_col":"rue Paris mision 34","heure_matin_col":"7","heure_apresmatin_col":"5","type":"collection","imagePath":"mmmmmmmmmmmm"}]
I want to know how to extract for example creator from this Json.
You can use a third-party JSON parser, like Google GSON, as you're already developing for Android. Java does not seem to contain a built-in JSON parser.
See this answer.
hello i have Json response like this
[
{
"question": "hhhhh",
"question_answer": "hhhh ",
"question_type": "question type",
"questioner_age": "questioner age",
"questioner_city": "questioner city",
"questioner_country": "questioner country",
"questioner_name": "questioner name",
"questioner_sex": "questioner sex",
"comments_allowed": "1",
"question_id": "63",
"question_date": "05/08/2017 - 19:33",
"is_public": "1"
},
{
"question": "hhhh !!",
"question_answer": "hhhh",
"question_type": [],
"questioner_age": [],
"questioner_city": [],
"questioner_country": [],
"questioner_name": "hhhhh",
"questioner_sex": [],
"comments_allowed": "1",
"question_id": "57",
"question_date": "04/30/2017 - 14:24",
"is_public": "1"
}
]
if the column is null will return as an array like this "question_type": [],
if not will return as a string !
so i tried to get this response on retrofit but i failed and always got this error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 4 column 2 path $
after i searched in the internet i tried something like this but its not working !!
Gson gson = new Gson();
String json = response.body().toString();
if (json instanceof String)
{
MyQuestionModelString parseObject = gson.fromJson(json, MyQuestionModelString.class);
apiCallResponse.onSuccess(parseObject,responseMessage);
}else {
MyQuestionModel parseObject = gson.fromJson(json, MyQuestionModel.class);
apiCallResponse.onSuccess(parseObject,responseMessage);
}
any help !
UPDATAE !
this is my model for this response and same error !!!
public class MyQuestionModel {
#SerializedName("question")
#Expose
private String question;
#SerializedName("question_answer")
#Expose
private String questionAnswer;
#SerializedName("question_type")
#Expose
private List<Object> questionType = null;
#SerializedName("questioner_age")
#Expose
private List<Object> questionerAge = null;
#SerializedName("questioner_city")
#Expose
private List<Object> questionerCity = null;
#SerializedName("questioner_country")
#Expose
private List<Object> questionerCountry = null;
#SerializedName("questioner_name")
#Expose
private String questionerName;
#SerializedName("questioner_sex")
#Expose
private List<Object> questionerSex = null;
#SerializedName("comments_allowed")
#Expose
private String commentsAllowed;
#SerializedName("question_id")
#Expose
private String questionId;
#SerializedName("question_date")
#Expose
private String questionDate;
#SerializedName("is_public")
#Expose
private String isPublic;
}
My Main issue that how to define this field ! question_type
screen shot
During the parsing of json if the SerializedName key is not found it will throw an exception. Use #Expose to let the deserializer to know that this field can be null. Here is a similar Model of your mentioned response
public class ResponsePojo {
List<Data> data;
public class Data {
#Expose
#SerializedName("question")
String question;
#Expose
#SerializedName("question_answer")
String questionAnswer;
#Expose
#SerializedName("question_type")
String questionType;
#Expose
#SerializedName("questioner_age")
String questionerAge;
#Expose
#SerializedName("questioner_city")
String questionerCity;
#Expose
#SerializedName("questioner_country")
String questionerCountry;
#Expose
#SerializedName("questioner_name")
String questionerName;
#Expose
#SerializedName("questioner_sex")
String questionerSex;
#Expose
#SerializedName("comments_allowed")
String commentsAllowed;
#Expose
#SerializedName("question_id")
String questionId;
#Expose
#SerializedName("question_date")
String questionDate;
#Expose
#SerializedName("is_public")
String isPublic;
}
}
You must indicate which paramters or objects in the model are optional with #Exposed tag.
Example
#Expose
#SerializedName("question_type")
private String mQuestionType;
You problem is
ava.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 4 column 2 path $
If your json code is [...],your return is JSONArray , you can use Gsonto parse it to List<Object> .
If your json code is {...},your return is JSONObject , you can use Gsonto parse it to Object .
So you should use List<MyQuestionModel> to get parsed data .
Change MyQuestionModel to List<MyQuestionModel> in your call code .
Sample
Call<List<MyQuestionModel>> getData();
And my code for doing it .
JSONEntity for you json
public class JSONEntity {
/**
* question : hhhhh
* question_answer : hhhh
* question_type : question type
* questioner_age : questioner age
* questioner_city : questioner city
* questioner_country : questioner country
* questioner_name : questioner name
* questioner_sex : questioner sex
* comments_allowed : 1
* question_id : 63
* question_date : 05/08/2017 - 19:33
* is_public : 1
*/
private String question;
private String question_answer;
private String question_type;
private String questioner_age;
private String questioner_city;
private String questioner_country;
private String questioner_name;
private String questioner_sex;
private String comments_allowed;
private String question_id;
private String question_date;
private String is_public;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getQuestion_answer() {
return question_answer;
}
public void setQuestion_answer(String question_answer) {
this.question_answer = question_answer;
}
public String getQuestion_type() {
return question_type;
}
public void setQuestion_type(String question_type) {
this.question_type = question_type;
}
public String getQuestioner_age() {
return questioner_age;
}
public void setQuestioner_age(String questioner_age) {
this.questioner_age = questioner_age;
}
public String getQuestioner_city() {
return questioner_city;
}
public void setQuestioner_city(String questioner_city) {
this.questioner_city = questioner_city;
}
public String getQuestioner_country() {
return questioner_country;
}
public void setQuestioner_country(String questioner_country) {
this.questioner_country = questioner_country;
}
public String getQuestioner_name() {
return questioner_name;
}
public void setQuestioner_name(String questioner_name) {
this.questioner_name = questioner_name;
}
public String getQuestioner_sex() {
return questioner_sex;
}
public void setQuestioner_sex(String questioner_sex) {
this.questioner_sex = questioner_sex;
}
public String getComments_allowed() {
return comments_allowed;
}
public void setComments_allowed(String comments_allowed) {
this.comments_allowed = comments_allowed;
}
public String getQuestion_id() {
return question_id;
}
public void setQuestion_id(String question_id) {
this.question_id = question_id;
}
public String getQuestion_date() {
return question_date;
}
public void setQuestion_date(String question_date) {
this.question_date = question_date;
}
public String getIs_public() {
return is_public;
}
public void setIs_public(String is_public) {
this.is_public = is_public;
}
}
And the code for parse it .
Gson gson = new Gson();
String jsonString = response.body().string();
Type type = new TypeToken<List<JSONEntity>>() {
}.getType();
List<JSONEntity> datas = gson.fromJson(jsonString, type);
EDIT
If your response is JSONArray , you can try like this .
List<JSONEntity> datas = response.body();
Try to change your JSON Structure
First Approach
To
If the column is null return "question_type": null,else show "question_type": "value"
Instead
If the column is null will return as an array like this "question_type": [], if not will return as a string!
Second Approach Without changing Json structure
Handling Dynamic JSON Using Gson
Try this:
You have to use deserialize to parse dynamic datatype in json
In the reponse pojo use object
Ex:
Call<Object> call = //your API call ResponsePojo instead use `Object`
call.enqueue(new Callback<Object>()
{
#Override
public void onResponse(Response<Object> response, Retrofit retrofit)
{
try {
JSONArray jsonArray=new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(ServerResponse.class, new ServerResponse.OptionsDeserilizer())
.create();
ServerResponse serverResponse=gson.fromJson(jsonArray.get(i).toString(), ServerResponse.class);
System.out.println(serverResponse);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t)
{
///Handle failure
}
});
Use this ServerResponsePojo with JsonDeserializer
import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class ServerResponse {
#SerializedName("question")
#Expose
private String question;
#SerializedName("question_answer")
#Expose
private String questionAnswer;
private String questionerName;
#SerializedName("comments_allowed")
#Expose
private String commentsAllowed;
#SerializedName("question_id")
#Expose
private String questionId;
#SerializedName("question_date")
#Expose
private String questionDate;
#SerializedName("is_public")
#Expose
private String isPublic;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getQuestionAnswer() {
return questionAnswer;
}
public void setQuestionAnswer(String questionAnswer) {
this.questionAnswer = questionAnswer;
}
/* public List<OptionValue> getQuestionerAge() {
return questionerAge;
}
public void setQuestionerAge(List<OptionValue> questionerAge) {
this.questionerAge = questionerAge;
}
public List<OptionValue> getQuestionerCity() {
return questionerCity;
}
public void setQuestionerCity(List<OptionValue> questionerCity) {
this.questionerCity = questionerCity;
}
public List<OptionValue> getQuestionerCountry() {
return questionerCountry;
}
public void setQuestionerCountry(List<OptionValue> questionerCountry) {
this.questionerCountry = questionerCountry;
}
*/
public String getQuestionerName() {
return questionerName;
}
public void setQuestionerName(String questionerName) {
this.questionerName = questionerName;
}
/*
public List<OptionValue> getQuestionerSex() {
return questionerSex;
}
public void setQuestionerSex(List<OptionValue> questionerSex) {
this.questionerSex = questionerSex;
}*/
public String getCommentsAllowed() {
return commentsAllowed;
}
public void setCommentsAllowed(String commentsAllowed) {
this.commentsAllowed = commentsAllowed;
}
public String getQuestionId() {
return questionId;
}
public void setQuestionId(String questionId) {
this.questionId = questionId;
}
public String getQuestionDate() {
return questionDate;
}
public void setQuestionDate(String questionDate) {
this.questionDate = questionDate;
}
public String getIsPublic() {
return isPublic;
}
public void setIsPublic(String isPublic) {
this.isPublic = isPublic;
}
public class OptionValue {
}
public void setQuestionType(String questionType) {
this.questionType = questionType;
}
String questionType;
public static class OptionsDeserilizer implements JsonDeserializer<ServerResponse> {
#Override
public ServerResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Type listType = new TypeToken<ServerResponse>() {
}.getType();
ServerResponse options = (ServerResponse) new Gson().fromJson(json, listType);
JsonObject jsonArrayValue = json.getAsJsonObject();
for (int i = 0; i < jsonArrayValue.size(); i++) {
JsonObject jsonObject = jsonArrayValue.getAsJsonObject();
if (jsonObject.has("question_type")) {
JsonElement elem = (JsonElement) jsonObject.get("question_type");
if (elem != null && !elem.isJsonNull() && !elem.isJsonArray()) {
String valuesString = elem.getAsString();
if (!TextUtils.isEmpty(valuesString)) {
options.setQuestionType(valuesString);
} else {
options.setQuestionType("");
}
//Do your other stuffs
}
}
}
return options;
}
}
}
This is working happy codeing
Trying to convert a POJO to a Json representation , my output is quite surprising : empty !
Here the POJO class :
public class AccountDTO extends BasicDBObject {
/**
*
*/
public static final String COLLECTION_NAME = "account-data";
private static final long serialVersionUID = 1L;
private String customerFirstName;
private String customerLastName;
private long customerId;
private String IBAN;
private float balance;
private String accountCurrency;
public AccountDTO(Account account, Customer customer) {
super();
this.customerFirstName = customer.getFirstname();
this.customerLastName = customer.getLastname();
this.customerId = customer.getCustomerId();
this.IBAN = account.getIBAN();
this.balance = account.getBalance();
this.accountCurrency = account.getAccountCurrency();
}
public String getCustomerName() {
return customerFirstName;
}
public void setCustomerName(String customerName) {
this.customerFirstName = customerName;
}
public String getCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String customerLastName) {
this.customerLastName = customerLastName;
}
public long getCustomerId() {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
public String getIBAN() {
return IBAN;
}
public void setIBAN(String iBAN) {
IBAN = iBAN;
}
public float getBalance() {
return balance;
}
public void setBalance(float balance) {
this.balance = balance;
}
public String getCustomerFirstName() {
return customerFirstName;
}
public void setCustomerFirstName(String customerFirstName) {
this.customerFirstName = customerFirstName;
}
public String getAccountCurrency() {
return accountCurrency;
}
public void setAccountCurrency(String accountCurrency) {
this.accountCurrency = accountCurrency;
}
#Override
public String toString() {
return "AccountDTO [customerFirstName=" + customerFirstName + ", customerLastName=" + customerLastName
+ ", customerId=" + customerId + ", IBAN=" + IBAN + ", balance=" + balance + ", accountCurrency="
+ accountCurrency + "]";
}
}
The converter :
public abstract class AccountDTODigester {
public static String digestJavaToJson(AccountDTO dto){
Gson gson = new Gson();
String json = gson.toJson(dto);
return json;
}
}
Code with jackson :
public abstract class AccountDTODigester {
public static String digestJavaToJson(AccountDTO dto) throws JsonProcessingException{
ObjectMapper mapper = new ObjectMapper();
String jsonInString = new String();
jsonInString = mapper.writeValueAsString(dto);
return jsonInString;
}
}
And finnaly the runner :
public class DAOTest {
AccountDTO accountDTO;
#Before
public void initialize(){
Account account = new Account("FRkk BBBB BGGG GGCC CCCC CCCC CKK", 0, "euro");
Customer customer = new Customer("XXXXXX", "YYYYYY", 1, account);
this.accountDTO = new AccountDTO(account, customer);
}
#Test
public void toJson(){
Assert.assertNotEquals(AccountDTODigester.digestJavaToJson(accountDTO),new String("{}"));
}
Console output :
AccountDTO [customerFirstName=XXXXXX, customerLastName=YYYYYY, customerId=1, IBAN=FRkk BBBB BGGG GGCC CCCC CCCC CKK, balance=0.0, accountCurrency=euro]
{}
When I run the test, my json string is { }and my test is mark as failed.
Gson seems to ver very easy to use, I don't understand why I got this empty Json instead a String filled with a json representation of my AccountDTO object
Ok I found solution :
My JSON was null because extends BasicDBObject , the serialization seems to be jammed by this.
Still looking for a better explication, but now my json is ok.
Given I have the following json:
{
"Company": {
"name": "cookieltd",
"type": "food",
"franchise_location": [
{
"location_type": "town",
"address_1": "5street"
},
{
"location_type": "village",
"address_1": "2road"
}
]
}
}
How can it be binded to the following object classes using Jackson?:
1) Company class
public class Company
{
String name, type;
List<Location> franchise_location = new ArrayList<Location>();
[getters and setters]
}
2) Location class
public class Location
{
String location_type, address_1;
[getters and setters]
}
I have done:
String content = [json above];
ObjectReader reader = mapper.reader(Company.class).withRootName("Company"); //read after the root name
Company company = reader.readValue(content);
but I am getting:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "franchise_location"
As far as I can tell, you are simply missing an appropriately named getter for the field franchise_location. It should be
public List<Location> getFranchise_location() {
return franchise_location;
}
(and the setter)
public void setFranchise_location(List<Location> franchise_location) {
this.franchise_location = franchise_location;
}
Alternatively, you can annotate your current getter or field with
#JsonProperty("franchise_location")
private List<Location> franchiseLocation = ...;
which helps to map JSON element names that don't really work with Java field name conventions.
The following works for me
public static void main(String[] args) throws Exception {
String json = "{ \"Company\": { \"name\": \"cookieltd\", \"type\": \"food\", \"franchise_location\": [ { \"location_type\": \"town\", \"address_1\": \"5street\" }, { \"location_type\": \"village\", \"address_1\": \"2road\" } ] } }";
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.reader(Company.class).withRootName(
"Company"); // read after the root name
Company company = reader.readValue(json);
System.out.println(company.getFranchise_location().get(0).getAddress_1());
}
public static class Company {
private String name;
private String type;
private List<Location> franchise_location = new ArrayList<Location>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Location> getFranchise_location() {
return franchise_location;
}
public void setFranchise_location(List<Location> franchise_location) {
this.franchise_location = franchise_location;
}
}
public static class Location {
private String location_type;
private String address_1;
public String getLocation_type() {
return location_type;
}
public void setLocation_type(String location_type) {
this.location_type = location_type;
}
public String getAddress_1() {
return address_1;
}
public void setAddress_1(String address_1) {
this.address_1 = address_1;
}
}
and prints
5street
my solution for JSON is always GSON, you can do some research on that, as long as you have the correct structure of class according to the JSON, it can automatically transfer from JSON to object:
Company company = gson.fromJson(json, Company.class);
GSON is so smart to do the convertion thing!
enjoy GSON !