将没有根元素的Json转换为对象?使用Gson,Ksoap2,Json.NET

时间:2014-03-11 19:24:41

标签: android json serialization gson ksoap2

在我的Android应用程序中,我从我的网络服务获得此响应:

[
{
 "bookNum":1,
 "title":"Halo the fall",
 "author":"Erick Nylum"
},
{
 "bookNum":2,
 "title":"Halo contact",
 "author":"Erick Nylum"
}
]

在android中我试图使用这个json转换为数组或列表对象,因为我没有根元素

  
        btnConsumer = (Button) this.findViewById(R.id.button1);
    btnConsumer.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            SoapObject request=new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);       
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.setOutputSoapObject(request);
            envelope.dotNet=true;       
            HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);// because AndroidHttpTransport now is d
            try {
                httpTransport.debug = true; // ?
                httpTransport.call(SOAP_ACTION, envelope);
                Object response = (Object) envelope.getResponse();
                lblView.setText(response.toString());

                String jsonData= response.toString();
                JSONObject json= new JSONObject(jsonData);
                JSONObject data= json.getJSONObject("book");//no root ERROR

            }catch (JSONException e) {
                    // TODO: handle exception
                e.printStackTrace();
            } catch (Exception e) {
                // TODO: handle exception
                lblView.setText(e.toString());
                // lblView.setText(e.getMessage());
            }           
        }
    });

jsonData是我的JSON字符串,我不知道如何转换为这个对象。

public class books {
            @SerializedName("bookNum")
                private String BookNum;
                @SerializedName("title")
                private String Title;
                @SerializedName("author")
                private String Author;

                public books() {
                    // contructor vacio
                }

                public books(String bookNum, String title, String author) {
                    super();
                    this.setBookNum(bookNum);
                    this.setTitle(title);
                    this.setAuthor(author);
                }

                public String getBookNum() {
                    return BookNum;
                }

                public String getTitle() {
                    return Title;
                }

                public String getAuthor() {
                    return Author;
                }

                public void setBookNum(String bookNum) {
                    BookNum = bookNum;
                }

                public void setTitle(String title) {
                    Title = title;
                }

                public void setAuthor(String author) {
                    Author = author;
                }

            }

我的网络服务

  
[WebMethod(Description = "try return a LIST of book object in Json format using Newtonsoft")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string ShowAllBooks()
{
    string url = "Server=localhost; database=books; password=system; user=sa;";
    MySqlConnection conn = new MySqlConnection(url);
    conn.Open();

    MySqlCommand command = conn.CreateCommand();
    //select
    command.CommandText = ("select * from reading");
    command.Connection = conn;
    MySqlDataReader reader = command.ExecuteReader();

    List<Book> listaBooks = new List<Book>();

    while (reader.Read())
    {
        Book book = new Book();
        book.bookNum = Convert.ToInt16(reader.GetString(0));
        book.title = reader.GetString(1).ToString();
        book.author = reader.GetString(2).ToString();
        listaBooks.Add(book);
    }
    command.Connection.Close();

    //var settings = new JsonSerializerSettings();
    //settings.TypeNameHandling = TypeNameHandling.Objects;

    //var typebook = Type.GetType("WS_Basico.Book");
    //string json = JsonConvert.SerializeObject(listaBooks,Formatting.Indented, settings); 
    string json = JsonConvert.SerializeObject(listaBooks, Formatting.Indented);

    return json;
}  

但我不能,我看到的所有方法(很多)通常使用“根元素”对象名称,在我的情况下我没有。 这有什么不对? 我遵循这个video,但他的JSON(对象名称)中有一个根元素。

有人请给我教程或链接或示例代码吗?


非常感谢@Paresh ..你创造了我的一天..在你的帮助下我仍然继续......实际上我创建了一个接收jsonData的方法,并将数据放在listView之后link ..是正确的方法吗?

  
protected void ShowInView(String jsonData) {
    // TODO Auto-generated method stub
    JSONArray arrayResponse;

    try {
        arrayResponse = new JSONArray(jsonData);
        for (int i = 0; i < arrayResponse.length(); i++) {
            JSONObject book = arrayResponse.getJSONObject(i);
            bookArrayList.add(Integer.toString(book.getInt("bookNum"))+" - "+book.getString("title"));
        }
        bookList.setAdapter(bookAdapter);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

谢谢!

1 个答案:

答案 0 :(得分:2)

问题在这里:

JSONObject json= new JSONObject(jsonData);
JSONObject data= json.getJSONObject("book");//no root ERROR

<强>解决方案: 问题是你得到JSONArray作为响应,但是你正在用响应字符串创建JSONObject。

JSONArray arrayResponse = new JSONArray(jsonData);  // correct way

现在,要获取子JSON对象,您必须遍历JSONArray。

for(int i=0; i<arrayResponse.length(); i++)
{
   JSONObject subObj = arrrayResponse.getJSONObject(i);
    // Now you can fetch strings/int and other values from object.
}