我是J2ME中JSON编程的新手。如何在J2ME中获取和设置JSONObject,JSONArray
我发现Json用于像XML那样交换数据。
我想知道从JSONtoObject在Array对象的交换,反之亦然
下面写的代码,我从JSON转换为对象,反之亦然。
但我不知道如何为复杂的数据结构不喜欢阵列等
//应用程序加载器
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class AppLoader extends MIDlet {
public AppLoader() {
// TODO Auto-generated constructor stub
// Converting Object to JSON
UserData data=new UserData();
data.setId(10);
data.setName("Yatin");
data.setDescription("Testing JSON in J2ME");
System.out.println("Convert to JSON"+data.toJSON());
//Convert JSON to Object
String sample="{\"id\":99,\"name\":\"Tester\",\"description\":\"This is JSON Data\"}";
UserData data2=new UserData();
data2.fromJSON(sample);
System.out.println("Convert from JSON "+data2);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
}
在这个类中,我创建getter和setter的String类型对象,然后创建的JSONObject创建JSON对象创建一个JSON对象,然后反之亦然按功能toJSON()
和fromJSON()
//用户数据类
import org.json.me.JSONException;
import org.json.me.JSONObject;
public class UserData {
private int id;
private String name;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString()
{
return getId()+"-"+getName()+"-"+getDescription();
}
public String toJSON() {
// TODO Auto-generated method stub
JSONObject inner=new JSONObject();
try {
inner.put("id",getId());
inner.put("description", getDescription());
inner.put("name", getName());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inner.toString();
}
public void fromJSON(String jsonString) {
// TODO Auto-generated method stub
try {
JSONObject json=new JSONObject(jsonString);
setId(json.getInt("id"));
setDescription(json.getString("description"));
setName(json.getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我找到了更好的链接,这个问题
http://jimmod.com/blog/2011/09/java-me-j2me-json-implementation-for-array-object/
这是一个很好的方法谢谢 – Yatin 2012-03-26 14:09:22
你还有这个罐子吗?我试图从源文件创建它,但我可能做错了什么,因为我不能得到它的工作:S https://github.com/upictec/org.json.me – eddy 2014-05-23 23:47:58
是的,请我找不到任何地方的瓶 – Axel 2014-05-24 12:43:03