如何從String中獲取List對象,添加列表中的新元素並將其重新設置爲字符串。我使用JSON和傑克遜,創建類名單的元素:Java字符串到對象的列表
public class WeightDataJson {
private String weightValue;
private String dateValue;
public WeightDataJson(String weightValue,String dateValue){
this.weightValue=weightValue;
this.dateValue=dateValue;
}
public String getWeightValue() {
return weightValue;
}
public void setWeightValue(String weightValue) {
this.weightValue = weightValue;
}
public String getDateValue() {
return dateValue;
}
public void setDateValue(String dateValue) {
this.dateValue = dateValue;
}
}
和我的改變列表代碼和字符串:
String myWeightData = preferencesWeight.get();
List<WeightDataJson> myList = new Vector<WeightDataJson>();
ObjectMapper jsonMapper = new ObjectMapper();
try {
myList = jsonMapper.readValue(myWeightData, new TypeReference<List<WeightDataJson>>(){});
} catch (IOException e) {
e.printStackTrace();
}
WeightDataJson newWeightData = new WeightDataJson(editText.getText().toString(),"213123");
myList.add(newWeightData);
JSONObject myJson=new JSONObject();
for(int i=0;i<myList.size();i++){
try {
myJson.put("weightValue",myList.get(i).getWeightValue());
myJson.put("dateValue",myList.get(i).getDateValue());
} catch (JSONException e) {
e.printStackTrace();
}
}
String toSave ="["+myJson.toString()+"]";
Toast.makeText(getActivity(),"zapisuje: "+toSave,Toast.LENGTH_LONG).show();
preferencesWeight.save(toSave);
WeightDataProvider weightDataProvider = new WeightDataProvider(addIcon,deleteIcon,editText.getText().toString(),"213123");
weightAdapter.add(weightDataProvider);
myWeightData
是「基本」字符串(這是可能的,它是空的) ,我不知道,但可能有問題,因爲jakcson字符串必須像[{element1},{element2}]
和Json對象給{element1},{element2}
所以我把那裏String toSave ="["+myJson.toString()+"]"
。
如果基本的字符串是[{weightValue":"50","dateValue":"34234"}]
我有一個錯誤的行myList=jsonmapper.readValue~~
:
07-30 03:59:04.407 11837-11837/com.plan.aplikacjamobilna W/System.err: com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.plan.aplikacjamobilna.WeightDataJson]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
07-30 03:59:04.407 11837-11837/com.plan.aplikacjamobilna W/System.err: at [Source: [{"weightValue":"14","dateValue":"213123"}]; line: 1, column: 3] (through reference chain: java.util.ArrayList[0])
有另一種方式來解決我的問題呢?
您是否嘗試過加入一個默認的構造類似的錯誤消息說,它缺少? – azurefrog
你的意思是WeightDataJson的構造函數嗎? – barmi
是的。您尚未爲該類定義默認構造函數,並且如果您已經定義了任何自己的類,java將不會自動創建一個。我期望傑克遜正在嘗試創建一個空白對象,然後向其中注入值,而這是默認構造函數無法實現的。 – azurefrog