2017-02-17 2 views
0

これはString []であるデータモデルです。次のコードを使用してモデルをJSONObjectに変換しようとします。文字列配列のJavaオブジェクトをフィールドとしてJSONObjectに変換

public class CheckList { 
    private String id = "123"; 
    private String Q1 = "This is Question 1"; 
    private String[] Q2 = ["Part 1", Part 2"]; 

    public CheckList (String, id, String Q1, String[] Q2){ 
     ... 
    } 
} 

CheckList checklist = new Checklist("123", "This is Question 1", ["Part 1", "Part 2"] 

JSONObject test = new JSONObject(checklist); 

String []が正しく変換されていません。上記のコードでは、私はJSONObjectは次のようになりたい:

{ 
    id: 123, 
    Q1: This is Question 1, 
    Q2: [Part 1, Part 2] 
} 

が、私はこのようJSONObjectを取得しています:

{ 
    id: 123, 
    Q1: This is Question 1, 
    Q2: [{"bytes":[{},{},{},{}],"empty":false},{"bytes":[{},{},{},{}],"empty":false}] 
} 

は、この問題を解決する方法はありますか?前もって感謝します。

答えて

0

あなたはそれがとても効率的だGsonを使用することができます。

class CheckList { 
    private String id = "123"; 
    private String Q1 = "This is Question 1"; 
    private String[] Q2 = {"Part 1", "Part 2"}; 
} 


final String jsonObject = new Gson().toJson(new CheckList()); 

System.out.print(jsonObject); 

出力:

{ 
    "id": "123", 
    "Q1": "This is Question 1", 
    "Q2": [ 
     "Part 1", 
     "Part 2" 
    ] 
} 
0

JSONObjectと にステップバイステップでエントリを入れ、最初にArrayList<String>に変換します。

ArrayList<String> list = new ArrayList<String>(); 
list.add("Part 1"); 
list.add("Part 2"); 

JSONObject test = new JSONObject(); 
test.put("id", 123); 
test.put("Q1","This is Question 1"); 
test.put("Q2", new JSONArray(list)); 
+0

お世話になりました。私はモデルをjsonに直接変換するソリューションを探しています。私の実際のチェックリストモデルは20のフィールドを持っているので、あなたのソリューションは私のユースケースに適していません。 – SL07

1

あなたは、配列をデシリアライズするCheckListクラス内JsonArrayを使用する必要があります。ただし、実装で許可されている場合は、Jacksonを使用してオブジェクトをjsonに変換することができます。使いやすく、JsonArrayなどのビットを必要としません。ジャクソンとhere'sドキュメントの

public class CheckList { 
    private String id = "123"; 
    private String Q1 = "This is Question 1"; 
    private String[] Q2; 

    public CheckList (String id, String Q1, String[] Q2){ 
     this.id = id; 
     this.Q1 = Q1; 
     this.Q2 = Q2; 
    } 

    public String getId() { 
     return id; 
    } 

    public void setId(String id) { 
     this.id = id; 
    } 

    public String getQ1() { 
     return Q1; 
    } 

    public void setQ1(String q1) { 
     Q1 = q1; 
    } 

    public String[] getQ2() { 
     return Q2; 
    } 

    public void setQ2(String[] q2) { 
     Q2 = q2; 
    } 

    public static void main(String[] args) throws Exception{ 
     CheckList checklist = new CheckList("123", "This is Question 1", new String[]{"Part 1", "Part 2"}); 
     ObjectMapper objectMaapper = new ObjectMapper(); 
     System.out.println(objectMaapper.writeValueAsString(checklist)); 

    } 
} 

Here's Mavenの中央URL:下の例です。

関連する問題