0

Json文字列を配列に変換したい ここに私の現在のコードがあります

    String[] comments = json2.getString(KEY_COMMENT);

KEY_COMMENT は、複数のコメントを含む文字列です。コメントは php 配列に集められ、電話に Json 文字列として送り返されました。文字列を配列に変換するにはどうすればよいですか?

コメントがどのように見えるかの例はこれです

07-08 20:33:08.227: E/JSON(22615): {
"tag":"collectComments",
"success":1,
"error":0,
"numberOfComments":16,
"offsetNumber":1,
"comment":["test 16",
"test 15",
"test 14",
"test 13",
"test 12",
"test 11",
"test 10",
"test 9",
"test 8",
"test 7",
"test 6",
"test 5",
"test 4",
"test 3",
"test 2",
"test 1"]}n
4

3 に答える 3

0

デフォルトの JSON ライブラリを使用するには、次を試してください。

// json 文字列から使用可能なものに変換する JSONArray commentsArray = json2.JsonArray(KEY_COMMENT);

// 要素をループします int length = commentsArray.length() for (int index = 0; index < length; index++) { String comment = commentsArray.getString(index); System.out.println(コメント); }

詳細については、このチュートリアルをお勧めします http://www.vogella.com/articles/AndroidJSON/

于 2013-07-09T00:59:47.090 に答える
0

GSON は、Android で json オブジェクトを操作するための優れたツールであることがわかりました。JSONをJavaオブジェクトに変換するJavaライブラリです。

ここで確認できます: https://sites.google.com/site/gson/gson-user-guide#TOC-Array-Examples

配列を操作する例を次に示します。

Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};

// Serialization
gson.toJson(ints);     ==> prints [1,2,3,4,5]
gson.toJson(strings);  ==> prints ["abc", "def", "ghi"]

// Deserialization
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); 

あなたの場合、次のようにクラスを設定します。

public class Comment {
    public String tag;
    public String[] comments; 
    // define other elements (numberOffset, error...) if needed
}

次に、コードで json 応答を逆シリアル化します。

Comment item = gson.fromJson(jsonString, Comment.class); 
// Access the comments by 
String[] comments = item.comments;

// Access the tag
String tag = item.tag;  
于 2013-07-09T00:50:33.520 に答える