Android中的对象XML映射 [英] Object XML mapping in Android

查看:161
本文介绍了Android中的对象XML映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个基于客户端-服务器的基于模型的应用程序,其中客户端在Android中,服务器在PHP中.

I am developing a client-server Model-based application in which client is in Android and server in PHP.

我想将产品信息(例如名称,价格,说明)从客户端传输到服务器. 我已经阅读到可以通过封送/拆封或序列化来实现,但是所有教程和示例均使用Java.但是我需要在Android中.请指导我在Android中实施.还是有其他实现方式?任何示例将不胜感激.谢谢.

I want to transfer product information for example Name,Price,Description, from client to server. I have read that through marshaling/unmarshaling or serialization it can be achieved but all tutorials and example are in Java. But I need in Android. Please guide me to implement in Android. Or there is any other way to implement? Any example will b appreciated. Thanks.

推荐答案

看看json. Google为此提供了一个很好的库,称为"Gson".

Have a look on json. Google provides a nice Library called "Gson" for that.

以您的示例为例,您的服务器通过http发送的json表示形式可能是:

To stick to your example, a json representation send from your server via http could be:

{"name":"foo", "price":"1000", "description":"this is an item description"}

在您的应用中,您有一个类MyObject.class

In your app, you have a class MyObject.class

public class MyObject {
    private String name;
    private double price;
    private String description;

// all your other methods
}

然后您可以做:

MyObject obj = new Gson().fromJson(jsonString, MyObject.class)

然后瞧瞧,在一行中用字符串做成了一个对象.只要确保变量在json表示形式和类中具有相同的名称,那么Gson就会为您完成所有工作.您还可以使用String jsonString = new Gson().toJson(obj)在对象之外制作一个String表示形式.

and voila, made an object out of the string in one line. Just be sure that the variables have the same name in the json representation and the class, then Gson does all the work for you. You can also make a String representation out of the object with String jsonString = new Gson().toJson(obj).

这篇关于Android中的对象XML映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆