如何从Java中

时间:2017-06-22 14:48:22

标签: java arrays json string

基本上我从包含名为“references”的键的服务器获取JSON响应,该键是一个String数组。如果没有找到先前的引用或者填充了以前的引用,它可以为空。

以下是我从服务器获得的回复。

{"code":100,

 "name":"3PVxkvfKyUiBg3LN24ek23KceGg6350KSkLZ.html",

  "file":{
         "author":"test@test",

         "idx":"xihav-zupak-zonyf-bedid-cyvun-fahac-mykud",

         "name":"html_file",

         "references":[
                "relec-toluz",

                "rosah-vyzyh",

                "rikik-cinom"
        ]
   }
}

我现在正在做的事情不是很好,我首先解析引用的内容以确定引用的数量然后我创建新的String数组并将每个值放入其中。但是我想知道是否有任何正确的方法来做到这一点。

这是我写的代码,这不是一段很好的代码:

if(file.has("references")){
                String s = file.get("references").toString();
                int counter =0; 
                //determine the amount of elements (check if the references does not finish with ','
                if(s.length() > 2 &&  s.charAt(s.length()-2) != ','){
                    counter++;
                    System.out.println(s);
                    for(int i=0 ; i < s.length(); i++){ if( s.charAt(i) == ',' ) counter++;}
                }else {
                    counter++;
                    for(int i = 0; i < s.length() -2; i++){ if(s.charAt(i) == ',') counter++;}
                }
                JsonArray referencesList = new Gson().fromJson(s, JsonArray.class);

                if(s != null && s.length()>2 && counter !=0){
                    System.out.println("1");
                    references = new String[counter];
                    for(int i = 0 ; i < references.length ; i++){ references[i] = referencesList.get(i).getAsString();}
                }else references = new String[]{"No previous references found"};
            }

代码对我的需求工作得很好,但有没有其他方法可以更“正确”地做到这一点?

3 个答案:

答案 0 :(得分:0)

if you wan to do this properly, you need before to create a pojo class for your json

public class ClassName{

private String code;
private String name;
private MyFile file;
......
}

public class MyFile{

private String author;
private String idx;
......
}

Now after that, you're ready to map your json on your pojo object, you can do it easly using jackson.


for your documentation

https://github.com/FasterXML/jackson-docs

So you need to add jackson on your project and you can do something like this for your mapping.

ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'qdqsdqs'}";


//JSON from URL to Object
ClassName result = mapper.readValue(jsonInString , ClassName.class);

答案 1 :(得分:0)

一个好的开始是使用Json Parser解析Json。由于您正在使用Gson,因此您应该查看JsonParser来进行解析。最好不要手动完成。

一些关键步骤包括:

  1. 解析Json(我将把你给我的json用作String,但你可以轻松地从文件中解析它)并获得JsonElement
  2. 查看file的{​​{1}}成员,该成员又是JsonElement并查看JsonElement JsonElement成员,你知道的是references
  3. 遍历JsonArray并添加到字符串列表中。将字符串列表作为JsonArray

    返回
    String[]

答案 2 :(得分:0)

我正在自己解析而不是这样做。所以我重写了一些部分,删除了计数器部分,然后发现了JSonArray的size()方法,我之前没有检查过。

我的最后一段代码更短,更容易阅读。

 String[] references = null;

 String repCode = "
 {
   "code":100,

   "name":"3PVxkvfKyUiBg3LN24ek23KceGg6350KSkLZ.html",

   "file":{
     "author":"test@test",

     "idx":"xihav-zupak-zonyf-bedid",

     "name":"random",

     "references":[
            "relec-toluz",

            "rosah-vyzyh",

            "rikik-cinom"
      ]
   }
}"

字符串repCode是我从我查询的服务器获得的响应。

JsonObject file = new Gson().fromJson(repCode.get("file").toString(),JsonObject.class);

if(file.has("references") &&  file.get("references").isJsonArray()){
    JsonArray referencesList = file.get("references").getAsJsonArray();

    if(referencesList.size() != 0){
        references = new String[referencesList.size()];
        for(int i = 0 ; i < references.length ; i++){
             references[i] = referencesList.get(i).getAsString();
        }
    }else references = new String[]{"No previous references found"};
}

最后显示:

 for(String ref: references){
        System.out.println("Ref: " + ref);
    }

提供以下输出:

Ref: relec-toluz
Ref: rosah-vyzyh
Ref: rikik-cinom
相关问题