将没有根元素的Json转换为对象?使用Gson,Ksoap2,Json.NET [英] Convert Json without root element to object? using Gson, Ksoap2, Json.NET
问题描述
在我的android应用程序中,我从我的web服务获得了这个响应:
[
{
bookNum:1,
title:Halo the fall,
author:Erick Nylum
},
{
bookNum:2,
title:Halo contact,
author:Erick Nylum
}
]
>
btnConsumer =(Button)this.findViewById(R.id.button1);
btnConsumer.setOnClickListener(new View.OnClickListener(){
$ b @Override
public void onClick(View v){
// TODO自动生成的方法存根
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); //因为AndroidHttpTransport现在是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); //无根ERROR
} catch(JSONException e){
// TODO:处理异常
e.printStackTrace();
} catch(Exception e){
// TODO:处理异常
lblView.setText(e.toString());
// lblView.setText(e.getMessage());
}
}
});
jsonData是我的JSON字符串,我不知道如何转换为此对象。
public class books {
@SerializedName(bookNum)
private String BookNum ;
@SerializedName(title)
private String Title;
@SerializedName(作者)
私人字符串作者;
public books(){
// contructor vacio
}
public books(String bookNum,String title,String author){
super();
this.setBookNum(bookNum);
this.setTitle(title);
this.setAuthor(作者);
}
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 =尝试使用Newtonsoft返回JSON格式的图书对象列表)]
[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();
//选择
command.CommandText =(select * from reading);
command.Connection = conn;
MySqlDataReader reader = command.ExecuteReader();
列表< Book> listaBooks =新列表< Book>(); (读者。读())
{
书book = new Book();
while
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);
返回json;
}
但我不能,我看到的所有方法一个根元素通常是对象名称,在我的情况下,我没有一个。
它有什么不对?
我遵循这个视频但他在他的JSON(对象名称)中有一个根元素。
有人请给我教程或链接或示例代码吗?
非常感谢@Paresh ..你做了我的一天..在你的帮助下,我仍然继续前进。实际上,我创建了一个接收jsonData的方法,在此链接 ...是正确的方式吗?
protected void ShowInView(String jsonData){
// TODO自动生成的方法存根
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自动生成的catch块
e.printStackTrace();
$ / code $ / pre
谢谢!
解决方案 问题在这里:
<$ c $ jsonObject json = new JSONObject(jsonData);
JSONObject data = json.getJSONObject(book); //无根错误
解决方案:
问题在于您正在获取 JSONArray
作为响应,但您正在使用响应字符串创建JSONObject。
JSONArray arrayResponse = new JSONArray(jsonData); //正确的方法
现在,要获取子JSON对象,必须遍历JSONArray。 / b>
for(int i = 0; i< arrayResponse.length(); i ++)
{
JSONObject subObj = arrrayResponse.getJSONObject(i);
//现在你可以从对象中获取字符串/ int和其他值。
}
In my android application I'm getting this response from my web service:
[
{
"bookNum":1,
"title":"Halo the fall",
"author":"Erick Nylum"
},
{
"bookNum":2,
"title":"Halo contact",
"author":"Erick Nylum"
}
]
In android I'm trying to use this json to convert in an array or list object, because I don't have a root element
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 is my JSON string, I don't know how to transform to this object.
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;
}
}
My web services
[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;
}
But I can't, all methods that I saw (a lot) use a "root element" normally the object name, In my case I don't have one.
What it's wrong?
I follow this video but he has a root element in his JSON (the object name).
Somebody please give me tutorial or link or sample code?
thanks a lot @Paresh.. you made my day.. With your help I still go ahead .. Actually I create a method that receive the jsonData and put the data in a listView following this link ... is the right way?
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();
}
}
Thank you!
Issue is here:
JSONObject json= new JSONObject(jsonData);
JSONObject data= json.getJSONObject("book");//no root ERROR
Solution:
Issue is your are getting JSONArray
in response but you are creating JSONObject with the response string.
JSONArray arrayResponse = new JSONArray(jsonData); // correct way
Now, to get sub JSON objects, you have to iterate through the 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.
}
这篇关于将没有根元素的Json转换为对象?使用Gson,Ksoap2,Json.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!