【问题标题】:Java , put JsonObject into JsonArray, but JsonArray take the same value at the end of the for loopJava , 将 JsonObject 放入 JsonArray 中,但 JsonArray 在 for 循环结束时取相同的值
【发布时间】:2023-03-30 17:31:02
【问题描述】:

我是 Java 新手,在这段代码中,我试图将 JsonObect 放入 JsonArray 中,但问题是 JsonArray 只取最后一个值,并且在其中重复。

您不需要了解所有代码,只需了解有趣的部分

我把感兴趣的部分代码放在了 //******here******// code //******end here***** *// 如果要测试的话我也放了json文件

就我而言,我尝试将我的值放入 JsonObject 列表中,然后将其放入 JsonArray 中,但结果相同。

我也尝试过使用带有索引的哈希映射,但它仍然不起作用

如果您打印 JsonObject 变量“Alldate”,您可以看到它具有不同的值,但是当我将它们放入 JsonArray 数组“ArrayBuckets”时,您会看到 JsonArray 具有相同的值,即最后一个值。

我不明白,因为我的 jsonObject 和 Array 在同一个循环中。

谢谢。

代码如下:

package jsonbi.bi;

import java.io.FileReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;

import com.google.gson.Gson;

public class JsonBi9 {

    JSONParser parser = new JSONParser();
    JSONObject json;
    Object obj;
    Map.Entry<String, JsonNode> field;
    HashMap newmap = new HashMap();
    JsonFactory factory = new JsonFactory();
    private ObjectMapper mapper = new ObjectMapper();

    Gson gson = new Gson();

    JSONArray jsonArray = new JSONArray();
    JSONObject Alldate = new JSONObject();

    JSONObject BucketsObject = new JSONObject();
    JSONObject Groupe = new JSONObject();
    JSONObject Aggregations = new JSONObject();
    JSONObject TheJson = new JSONObject();

    JSONArray ArrayBuckets = new JSONArray();

     Hashtable ht = new Hashtable();



     int j =0;

    public JsonBi9() {

        try {

            // here I am readind the json file
            obj = parser.parse(new FileReader("myjson2.json"));

            ObjectMapper mapper = new ObjectMapper(factory);

            JsonNode rootNode = mapper.readTree(obj.toString());

            Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.getFields();

            JSONObject jsonObject = new JSONObject(obj.toString());


            // here I am reading the fields in the json fields
            while (fieldsIterator.hasNext()) {

                field = fieldsIterator.next();

                newmap.put(field.getKey(), field.getValue());

                if (field.getKey().equals("aggregations")) {

                    System.out.println("hugo");

                    JSONObject aggregations = jsonObject.getJSONObject("aggregations");

                    JSONObject groupe = aggregations.getJSONObject("groupe");

                    JSONArray buckets = groupe.getJSONArray("buckets");



    for (int i11a = 0; i11a < buckets.length(); i11a++) {



    JSONObject obj1bucket = buckets.getJSONObject(i11a);


                        JSONObject date11 = obj1bucket.getJSONObject("date");

                        JSONArray obj11bucket = date11.getJSONArray("buckets");



                        List<String> listSubbucket = new ArrayList<String>();

                        for (int i11 = 0; i11 < obj11bucket.length(); i11++) {

                            listSubbucket.add(obj11bucket.getJSONObject(i11).toString());

                            // System.out.println(obj11bucket.getJSONObject(i11).toString());

                        }

                        jsonArray = new JSONArray();

                        for (int i11 = 0; i11 < listSubbucket.size(); i11++) {

                            JSONObject SubBucket = new JSONObject();

                            SubBucket.put("buckets", listSubbucket.get(i11));


                            getdocument(obj1bucket, Alldate);



//******************************here ********************************//

                            // System.out.println(SubBucket);
                            Alldate.put("date", SubBucket);


                            ArrayBuckets.put(Alldate);

                        //*µµ if you want to print the jsonObject and array

                        //  System.out.println(Alldate);
                            // System.out.println(ArrayBuckets);*

//*********************************end here ******************************//



                        } // end first  for loop

                    } //end second for loop

                    Enumeration e = ht.elements();

                    while(e.hasMoreElements())
                      System.out.println(e.nextElement());



                    getdocument(groupe, Groupe);

                    Groupe.put("buckets", ArrayBuckets);

                    Aggregations.put("groupe", Groupe);
                    // System.out.println(Aggregations);

                } // fin du if

                else {

                    // System.out.println("Key: " + field.getKey() + "\tValue:"
                    // + field.getValue());

                    TheJson.put(field.getKey(), field.getValue());

                } // fin du else

            } // fin du while

            // I put all the documents
            TheJson.put("aggregations", Aggregations);

            System.out.println(TheJson);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void getdocument(JSONObject obj1bucket, JSONObject Alldate) {

        // get the json documents in the subbuckets
        int i = 0;
        // JSONObject buckectinfos1 = new JSONObject();
        for (Iterator key = obj1bucket.keys(); key.hasNext();) {

            Object jsonkeys;
            try {
                jsonkeys = obj1bucket.get((String) key.next());

                Object jsonvalues = obj1bucket.names().getString(i);

                String jsonInString = gson.toJson(jsonkeys);

                if (!jsonkeys.getClass().getName().equals("org.json.JSONObject")
                        && !jsonkeys.getClass().getName().equals("org.json.JSONArray")) {


                } // fin du if
                i++;

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } // fin du for

    }

}

这是我想放入 JsonArray“ArrayBuckets”中的 JsonObject“alldate”中的值:

{"date":{"buckets":"{\"key_as_string\":\"2017-05-03T00:00:00.000Z\",\"doc_count\":1,\"value\":{\"value\":1},\"key\":1493769600000}"},"doc_count":"1","key":"\"a\""}
{"date":{"buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":2,\"value\":{\"value\":3},\"key\":1493776800000}"},"doc_count":"1","key":"\"a\""}
{"date":{"buckets":"{\"key_as_string\":\"2017-05-03T00:00:00.000Z\",\"doc_count\":4,\"value\":{\"value\":5},\"key\":1493769600000}"},"doc_count":"4","key":"\"b\""}
{"date":{"buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":5,\"value\":{\"value\":6},\"key\":1493773200000}"},"doc_count":"4","key":"\"b\""}

但我只有在 JsonArray "ArrayBuckets" 中重复的最后一个值:

{"date":{"buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":5,\"value\":{\"value\":6},\"key\":1493773200000}"},"doc_count":"4","key":"\"b\""}

这是 Json 文件:“myjson2.json”

{ 
  "took": 7, 
  "timed_out": false, 
  "_shards": { 
    "total": 5, 
    "successful": 5, 
    "failed": 0 
  }, 
  "hits": { 
    "total": 10, 
    "max_score": 0, 
    "hits": [] 
  }, 
  "aggregations": { 
    "groupe": { 
      "doc_count_error_upper_bound": 0, 
      "sum_other_doc_count": 0, 
      "buckets": [ 
        { 
          "key": "a", 
          "doc_count": 1, 
          "date": { 
            "buckets": [ 
              { 
                "key_as_string": "2017-05-03T00:00:00.000Z", 
                "key": 1493769600000, 
                "doc_count": 1, 
                "value": { 
                  "value": 1 
                } 
              }, 
              { 
                "key_as_string": "2017-05-03T01:00:00.000Z", 
                "key": 1493776800000, 
                "doc_count": 2, 
                "value": { 
                  "value": 3 
                } 
              } 
            ] 
          } 
        }, 
        { 
          "key": "b", 
          "doc_count": 4, 
          "date": { 
            "buckets": [ 
              { 
                "key_as_string": "2017-05-03T00:00:00.000Z", 
                "key": 1493769600000, 
                "doc_count": 4, 
                "value": { 
                  "value": 5 
                } 
              }, 
              { 
                "key_as_string": "2017-05-03T01:00:00.000Z", 
                "key": 1493773200000, 
                "doc_count": 5, 
                "value": { 
                  "value": 6 
                } 
              } 

            ] 
          } 
        } 
      ] 
    } 
  } 
} 

这是代码的结果:

{  
   "_shards":"{\"total\":5,\"failed\":0,\"successful\":5}",
   "hits":"{\"hits\":[],\"total\":10,\"max_score\":0}",
   "took":"7",
   "timed_out":"false",
   "aggregations":{  
      "groupe":{  
         "doc_count_error_upper_bound":"0",
         "sum_other_doc_count":"0",
         "buckets":[  
            {  
               "date":{  
                  "buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":5,\"value\":{\"value\":6},\"key\":1493773200000}"
               },
               "doc_count":"4",
               "key":"\"b\""
            },
            {  
               "date":{  
                  "buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":5,\"value\":{\"value\":6},\"key\":1493773200000}"
               },
               "doc_count":"4",
               "key":"\"b\""
            },
            {  
               "date":{  
                  "buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":5,\"value\":{\"value\":6},\"key\":1493773200000}"
               },
               "doc_count":"4",
               "key":"\"b\""
            },
            {  
               "date":{  
                  "buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":5,\"value\":{\"value\":6},\"key\":1493773200000}"
               },
               "doc_count":"4",
               "key":"\"b\""
            }
         ]
      }
   }
}

【问题讨论】:

    标签: java arrays json loops for-loop


    【解决方案1】:

    不要在类范围内声明 Alldate 变量,而是在 for 循环中声明它。发生错误是因为您只有一个变量 JsonObject 可放入 JsonArray。所以解决方案是为每个循环创建每个不同的 JsonObject 变量。

    for (int i11 = 0; i11 < listSubbucket.size(); i11++) {
    
                                JSONObject Alldate = new JSONObject();
    
                                ...
    
    //******************************here ********************************//
    
                                // System.out.println(SubBucket);
                                Alldate.put("date", SubBucket);
    
    
                                ArrayBuckets.put(Alldate);

    或适合您的代码的东西。

    【讨论】:

      【解决方案2】:

      JSONObject 中只能有一个带有名称的条目。

      for (int i11 = 0; i11 < listSubbucket.size(); i11++) {
      
                              JSONObject SubBucket = new JSONObject();
      
                              SubBucket.put("buckets", listSubbucket.get(i11));
      
      
                              getdocument(obj1bucket, Alldate);
      
                              // System.out.println(SubBucket);
                              Alldate.put("date", SubBucket);
      
      
                              ArrayBuckets.put(Alldate);
      
                          //*µµ if you want to print the jsonObject and array
      
                          //  System.out.println(Alldate);
                              // System.out.println(ArrayBuckets);
      
      
      
                          } // end first  for loop
      

      执行此操作时,在每个循环中,您都会使用键“日期”覆盖 de 值。如果您想在 AllDate 中包含所有日期,则它必须是 JSONArray。

      您也可以将Alldate.put("date", SubBucket); 替换为Alldate.put("date" + i, SubBucket);

      【讨论】:

        猜你喜欢
        • 2021-05-09
        • 2020-01-23
        • 2021-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-13
        • 2016-05-24
        • 1970-01-01
        相关资源
        最近更新 更多