【问题标题】:JSON/Java/Android: deserialisation from a String to a ArrayList<Strings>JSON/Java/Android:从字符串反序列化为 ArrayList<Strings>
【发布时间】:2011-12-02 21:35:58
【问题描述】:

我正在寻找几个小时来将字符串反序列化为其以前的形式,即 ArrayList。 毫无疑问,网上有很多例子。但我尝试的每一个都至少缺少一个对象或命令。因此,没有一种方法可以实施,他们公布了。

服务器有以下实现:

for (String string:DBdata)
    {   //put each string in DBdata to a JSON-Object with key=time and value=value
        jSONString.put(string.substring(0, string.indexOf(",")), string.substring(string.indexOf(",")+1,string.indexOf(";")));
    }

DBdata 中的每个字符串都像 123234:1234567; (UnixTimeOrIndex:值;) 如果反序列化后的输出是二维的,也可以。

提前致谢。

【问题讨论】:

  • 考虑使用一些第三方库,如 GSON 和 Jackson,它们应该让开发者的生活更轻松。
  • Jackson 或 Google 的 json-simple 将是我的建议:code.google.com/p/json-simple

标签: java android json deserialization


【解决方案1】:

我自己写的: 可能不是最有效的解决方案,但它确实有效。主类中的所有内容都只是组装一个字符串进行测试。

package test;
import java.util.ArrayList;
import net.sf.json.JSONObject;
public class Tst {
public static void main(String[] args) {
        ArrayList<String> versuch=new ArrayList<String>();
        for(int i=1; i<11; i++){       
        String temp = "Time1234"+i+",MeanValue123"+i+";";
        System.out.println(temp);
        versuch.add(temp);
        }
        System.out.println(versuch);

        JSONObject jSONString = new JSONObject();
        for (String string:versuch)
        {   //put each string in DBdata to a JSON-Object with key=time and value=value
            jSONString.put(string.substring(0, string.indexOf(",")), string.substring(string.indexOf(",")+1,string.indexOf(";")));
        }
        String output="data.ID=1234."+jSONString.toString();
        System.out.println(output);
        System.out.println(JSONDeconstruct(output));
    }

    public static ArrayList<String> JSONDeconstruct (String st)
    {

        ArrayList<String> out=new ArrayList<String>();

        int begpos=st.indexOf("{");
        int endpos=st.indexOf("}");
        int index=0;

        String work=st.substring(begpos+1, endpos);
        String replaced=work.replace("\",\"", ",");
        work=replaced.replace("\":\"", ":");
        replaced=work.replace("\"","")+",definedend";
        System.out.println(replaced);

        while (!replaced.equals("definedend"))
        {           
            out.add(replaced.substring(0,replaced.indexOf(":"))+","+replaced.substring(replaced.indexOf(":")+1, replaced.indexOf(","))+";");

            String tempstring=replaced.substring(replaced.indexOf(",")+1);  
            replaced=tempstring;
            index++;
            System.out.println("loop disassembly step"+index+"   "+replaced);

        }


        return out;


    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    相关资源
    最近更新 更多