2017-06-22 138 views
1

基本上,即时从包含名为“引用”的字符串数组的服务器的服务器获取JSON响应。如果没有找到之前的参考或者以前的参考填充,它可以是空的。如何从Java中的JSON字符串填充字符串数组

这是我从服务器得到的响应。

{"code":100, 

"name":"3PVxkvfKyUiBg3LN24ek23KceGg6350KSkLZ.html", 

    "file":{ 
     "author":"[email protected]", 

     "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"}; 
      } 

的代码工作得很好了我的需要,但没有任何其他办法可以做到更“正确”?

+2

你没有使用'JSONParser'任何理由吗?检查出:https://stackoverflow.com/questions/43724937/how-to-parse-json-string-to-java-object-with-jackson – yogidilip

+0

@yogidilip以及我一直在使用Google的GSON为我的整个项目,因为我发现它更易于使用。这就是为什么。 – retArdos

+2

那么你绝对应该考虑使用Gson的'JsonParser'。将解析留给Gson,只处理生成的'JsonElement'。 – Ishnark

回答

0

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

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

String[] references = null; 

String repCode = " 
{ 
    "code":100, 

    "name":"3PVxkvfKyUiBg3LN24ek23KceGg6350KSkLZ.html", 

    "file":{ 
    "author":"[email protected]", 

    "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 
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); 
0

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

一些关键步骤包括:

  1. 解析JSON(我要你给我的JSON,并把它作为一个字符串,但你可以很容易地从文件中解析它),并获得JsonElement
  2. 看那JsonElementfile成员,这是又将JsonElement,并期待在这JsonElementreferences成员,你知道是JsonArray
  3. 遍历JsonArray并添加到字符串列表中。返回一个字符串该列表作为一个String[]

    public static void main(String[] args) { 
        String json = "{\"code\":100,\n" + 
          "\n" + 
          " \"name\":\"3PVxkvfKyUiBg3LN24ek23KceGg6350KSkLZ.html\",\n" +  
          "\n" + 
          " \"file\":{\n" + 
          "   \"author\":\"[email protected]\",\n" + 
          "\n" + 
          "   \"idx\":\"xihav-zupak-zonyf-bedid-cyvun-fahac-mykud\",\n" + 
          "\n" + 
          "   \"name\":\"html_file\",\n" + 
          "\n" + 
          "   \"references\":[\n" + 
          "    \"relec-toluz\",\n" + 
          "\n" + 
          "    \"rosah-vyzyh\",\n" + 
          "\n" + 
          "    \"rikik-cinom\"\n" + 
          "  ]\n" + 
          " }\n" + 
          "}"; 
        JsonElement element = new JsonParser().parse(json); 
        System.out.println(Arrays.toString(getReferences(element))); 
    
    } 
    
    private static String[] getReferences(JsonElement jsonElement) { 
        List<String> refList = new ArrayList<>(); 
        JsonArray references = jsonElement.getAsJsonObject().get("file").getAsJsonObject().get("references").getAsJsonArray(); 
        references.forEach((reference) -> refList.add(reference.getAsString())); 
        return refList.toArray(new String[0]); 
    }