【问题标题】:How to fill an array of String from a JSON String in Java如何在 Java 中从 JSON 字符串填充字符串数组
【发布时间】:2017-06-22 14:48:21
【问题描述】:

基本上我从服务器获得一个 JSON 响应,其中包含一个名为“references”的键,它是一个字符串数组。当没有找到以前的引用时,它可以是空的,也可以用以前的引用填充。

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

{"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"
        ]
   }
}

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

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

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

代码可以很好地满足我的需要,但有没有其他方法可以更“正确”地做到这一点?

【问题讨论】:

  • 有什么理由不使用JSONParser?签出:stackoverflow.com/questions/43724937/…
  • @yogidilip 我在整个项目中一直使用 Google 的 GSON,因为我发现它更易于使用。这就是为什么。
  • 那你一定要考虑使用Gson的JsonParser。将解析留给 Gson,只处理生成的 JsonElement
  • 同意大多数 cmets,不要使用“手动代码”,而是准备好并经过测试的解析器

标签: java arrays json string


【解决方案1】:
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);

【讨论】:

    【解决方案2】:

    使用 Json Parser 解析 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\":\"test@test\",\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]);
      }
      

    【讨论】:

      【解决方案3】:

      我是自己解析的,没有做对。所以我重写了一些部分,删除了对应的部分,然后发现了我以前没有检查过的 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-28
        • 1970-01-01
        • 2013-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多