如何在Java对象中转换字符串数组JSON

时间:2014-05-25 01:12:48

标签: java json unmarshalling

我需要将此String JSON转换为Java对象:

{"estabelecimento":[{"id":"5","idUsuario":"5","razaoSocial":"Bibi LTDA","nomeFantasia":"BibiPizza","telefone":"22121212","email":"ronaldo@bibi.com","gostaram":"0"},{"id":"8","idUsuario":"1","razaoSocial":"Nestor Latuf LTDA","nomeFantasia":"Nestor Sorvetes","telefone":"32343233","email":"nestor@Sorvete.com","foto":"","gostaram":"0"},{"id":"9","idUsuario":"1","razaoSocial":"Comercio Alimenticio Rivaldo","nomeFantasia":"Rogers Burguer","telefone":"210021020","email":"roger@gmail.com","foto":"","gostaram":"0"}]}

我试试这个,但不行:

 //JSONArray jArr = new JSONArray(br.toString());  

        //JSONObject jObj = new JSONObject(br.toString());

        //JSONArray jArr = jObj.getJSONArray("list");

        JSONArray jArr = new JSONArray(br.toString());

        for (int i=0; i < jArr.length(); i++) {
            JSONObject obj = jArr.getJSONObject(i);
            estabelecimento.setId(obj.getLong("id"));
            estabelecimento.setIdUsuario(obj.getLong("idUsuario"));
            estabelecimento.setRazaoSocial(obj.getString("razaoSocial"));
            estabelecimento.setNomeFantasia(obj.getString("nomeFantasia"));
            estabelecimento.setTelefone(obj.getString("telefone"));
            estabelecimento.setEmail(obj.getString("email"));
            estabelecimento.setGostaram(obj.getInt("gostaram"));

            estabelecimentoList.add(estabelecimento);
        }
        con.disconnect();

如何获取Java对象?有人可以帮忙吗? TKS。

2 个答案:

答案 0 :(得分:1)

您可以使用google的Gson lib:

public class MyClass {

    private int data1 = 100;
    private String data2 = "hello";
    private List<String> list = new ArrayList<String>() {
      {
        add("String 1");
        add("String 2");
        add("String 3");
      }
    };

    //getter and setter methods needed


}


String str = {"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]};
com.google.gson.Gson gson = new com.google.gson.Gson();

//To convert json string to class use fromJson
MyClass obj = gson.fromJson(str, MyClass .class);

//To convert class object to json string use toJson
String json = gson.toJson(obj);

答案 1 :(得分:0)

高层次的两个主要步骤:

  1. 从您的JSON生成Java类,例如:使用此生成器或类似工具:http://www.jsonschema2pojo.org/
  2. 使用Jackson处理器反序列化您的JSON文件:

     ObjectMapper mapper = new ObjectMapper();
     YourGeneratedClass obj = (YourGeneratedClass) mapper.readValue(new File("path-to-your-json-file"), YourGeneratedClass.class);
    
  3. 关于杰克逊的更多信息:http://jackson.codehaus.org/

    如果您对此感到满意,也可以手动创建YourGeneratedClass。