【问题标题】:How can I Json (or Gson) a class like "objects to string" and after "string to objects"我如何 Json(或 Gson)一个类,如“对象到字符串”和“字符串到对象”之后
【发布时间】:2012-04-03 14:24:07
【问题描述】:

我的问题是关于我使用跟随的课程时发生的错误:

public class ClassePai {

    private int ID;
    private String Nome;
    private ArrayList<ClasseFilho> listaParentes;

    public ClassePai( int id, String nome){

        this.ID = id;
        this.Nome = nome;       

        listaParentes = new ArrayList<ClasseFilho>();

    }

    public void addParente(ClasseFilho classeFilho) {

        listaParentes.add(classeFilho);

    }

    public ClasseFilho getParente( int index ){

        return listaParentes.get(index);

    }

    public int length(){

        return listaParentes.size();
    }

    public String Nome(){

        return this.Nome;
    }

    public int ID(){
        return this.ID;
    }

}

还有这个“儿子”类:

public class ClasseFilho {

    private String Nome;
    private String Grau;

    public ClasseFilho( String nome, String grau ){

        this.Nome = nome;
        this.Grau = grau;

    }

    public String Nome(){

        return this.Nome;
    }

    public String Grau(){
        return this.Grau;
    }

}

这是我的活动:

public class TesteClasseActivity extends Activity {

    private ClassePai cp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        cp = new ClassePai( 1, "Junior" );

        cp.addParente( new ClasseFilho( "Vinicius", "filho" ) );
        cp.addParente( new ClasseFilho( "Luciene", "namorada" ) );

        //old call returning error
        //Toast.makeText(getApplicationContext(), cp.length(), Toast.LENGTH_SHORT).show();

        Toast.makeText(getApplicationContext(), String.valueOf( cp.length() ), Toast.LENGTH_SHORT).show();

        cp.addParente( new ClasseFilho( "Veraldo", "pai" ) );
        cp.addParente( new ClasseFilho( "Sônia", "mãe" ) );

        Toast.makeText(getApplicationContext(), String.valueOf( cp.length() ), Toast.LENGTH_SHORT).show();

        ( (TextView) findViewById(R.id.edit) ).setText( cp.Nome() );

        Button bt = (Button) findViewById(R.id.button);

        bt.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {

                Toast.makeText(getApplicationContext(), cp.getParente(1).Nome(), Toast.LENGTH_SHORT).show();

            }
          });

            //my try of doing this, but don't work             

            JSONObject obj = new JSONObject();

            obj.put("teste", cp);

            // BUT unfortunatelly
            // 
            // obj.toString() returns this:
            //
            // {"teste":"my.package.name.ClassePai@40516650"}
            // 
            // BUT...


            //wondering on net, I've deceided to try Gson:

            //first part: object to string

            Gson obj = new Gson();

            obj.toJson(cp);

            String obj_in_xml = obj.toString();

            Toast.makeText( getApplicationContext() , obj_in_xml, Toast.LENGTH_SHORT).show();

            //no error, appear works fine, but...


            //second part: string to object

            Gson obj2 = new Gson();

            ClassePai new_cp = obj2.fromJson( obj_in_xml, ClassePai.class);

            Toast.makeText( getApplicationContext() , new_cp.Nome(), Toast.LENGTH_SHORT).show();

            //give me an error com.google.gson.stream.MalformedJsonException
            //and I could't find my properties in obj.toString(), but only codes like:
            //
            //adapter=com.google.gson.internal.bind.TypeAdapters$7@40529278]
            //
            // and don't find any of the object's string properties in the obj.toString() string
            //
            // what I'm doing wrong????


    }
}

如何以文本格式保存此对象和子对象,并在再次从字符串加载到对象后?

请帮帮我!!!

【问题讨论】:

  • 发布您的堆栈跟踪。甚至更好:自己阅读。您的问题以 90% 的概率以明文形式回答
  • 是的,请粘贴 logcat 消息,并指向引发异常的行。
  • 04-03 14:45:36.543: E/AndroidRuntime(262): 致命异常: main 04-03 14:45:36.543: E/AndroidRuntime(262): java.lang.RuntimeException:无法启动活动 ComponentInfo{br.junior.testeclasse/br.junior.testeclasse.TesteClasseActivity}:android.content.res.Resources$NotFoundException:字符串资源 ID #0xa 04-03 14:45:36.543:E/AndroidRuntime(262 ): 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) 这个你想要吗?
  • 可能。只需编辑您的问题并将 logcat sn-p 发布为代码

标签: android json class gson


【解决方案1】:

问题可能出在这里:

Toast.makeText(getApplicationContext(), cp.length(), Toast.LENGTH_SHORT).show();

这里的第二个参数必须是对字符串资源或字符串值的整数引用。如果您想将大小显示为 toast 消息,请使用此变体:

Toast.makeText(getApplicationContext(), String.valueOf(cp.length()), Toast.LENGTH_SHORT).show();

更新

要将 JSON 对象转换为字符串,请使用:

String myString = myJSONObject.toString();

字符串到 JSONObject:

JSONObject myJSONObject = getJSONObject(myString);

【讨论】:

  • 这很好用...为什么 Toast 不警告这个? Java中没有演员表检查吗?谢谢伙计...但是主要问题呢,如何使用 JSon 将对象传输到字符串,反之亦然?
  • 感谢@Bakyt,但这对我不起作用。请查看我更新的问题
【解决方案2】:

第一个问题是,您不能将 int 类型传递给方法“Toast.makeText”。您可以将 int 转换为 String 并显示它。通过 String lengthString = String.valueOf(cp.length()).

第二个问题你可以使用xml来保存和读取字符串。

    JSONObject person = new JSONObject();
    String spmnoName = "spmno";
    try{
        person.put("name", spmnoName);
        String getString = person.getString("name");
    }catch(JSONException ex){
        throw new RuntimeException(ex); 
    }

【讨论】:

  • 好的,演员表问题解决了......但是主要问题呢,如何使用 JSON 将对象传输到字符串,反之亦然?
  • 我不知道你为什么坚持使用json来保存字符串。 Json 是一个键/值对。你可以像这样使用json。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 2011-01-16
  • 1970-01-01
相关资源
最近更新 更多