![](/img/trans.png)
[英]How to use gson to serialize classes with custom object attributes in android?
[英]How to use Gson to serialize objects in android?
我想使用socket從Android客戶端向Java服務器發送2個對象(因為我正在開發遠程PC)。
AndroidClient.java
public class MainActivity extends Activity{
Socket client;
ObjectOutputStream oos;
OutputStream os;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SendObj so=new SendObj();
so.execute();
}
class SendObj extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... arg0) {
try {
client=new Socket("192.168.237.1",6566);
os=client.getOutputStream();
oos=new ObjectOutputStream(os);
Serializer ma=new Serializer(2, "Helllo");
Log.i("Serial",""+ma.name);
oos.writeObject(ma);
oos.writeObject(new String("Another Object from Client"));
oos.close();
os.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
@SuppressWarnings("serial")
class Serializer implements Serializable {
int num;
String name;
public Serializer(int num,String name){
this.name=name;
this.num=num;
}
}
JavaServer.java
public class ObjectReceiver {
static ServerSocket server;
static Socket client;
static ObjectInputStream ois;
static InputStream is;
public static void main(String[] arg) throws IOException, ClassNotFoundException{
server=new ServerSocket(6566);
System.out.println("Wait");
while(true){
client=server.accept();
System.out.println("Connected");
is=client.getInputStream();
ois=new ObjectInputStream(is);
try {
ObjectSerail or = (ObjectSerail) ois.readObject();
if(or!=null){
System.out.println("Done");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
@SuppressWarnings("serial")
class ObjectSerail implements Serializable{
int num;
String name;
public ObjectSerail(int num,String name){
this.name=name;
this.num=num;
}
}
}
當然我知道上面的方法不會起作用,因為它會產生ClassNotFoundException()
。 所以現在我想知道如何使用Gson庫來序列化和反序列化對象。 提前致謝。
gson可以在任何平台上與Java一起使用 - 不僅僅是Android。
使用gson序列化單個對象:
// Serialize a single object.
public String serializeToJson(MyClass myClass) {
Gson gson = new Gson();
String j = gson.toJson(myClass);
return j;
}
使用gson反序列化為單個對象。
// Deserialize to single object.
public MyClass deserializeFromJson(String jsonString) {
Gson gson = new Gson();
MyClass myClass = gson.fromJson(jsonString, MyClass.class);
return myClass;
}
正如你從例子中看到的那樣,gson非常神奇:)它實際上並不神奇 - 你需要確保至少一些東西:
確保您的類具有無args構造函數,以便gson庫可以輕松獲取實例。
確保屬性名稱與json中的屬性名稱匹配,以便gson庫可以將json中的字段映射到類中的字段。
另請參閱https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.