Java,把JsonObject放到JsonArray中,但JsonArray在for循环结束时取相同的值

时间:2017-05-10 09:12:00

标签: java arrays json loops for-loop

我是Java的新手,在这段代码中,我试图将JsonObect放在JsonArray中,但事情是JsonArray只取最后一个值而且它是重复的。

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

我已经在这里放置了有趣的代码部分// ******这里***** //代码// ******结束这里***** * //如果你想测试

我也放了json文件

就我而言,我试图将我的值放在List of 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

    }

}

这是JsonObject&#34; alldate&#34;中的值。我想把它放在JsonArray&#34; ArrayBuckets&#34;:

{"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&#34; ArrayBuckets&#34;中重复了最后一个值:

{"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文件:&#34; myjson2.json&#34;

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

2 个答案:

答案 0 :(得分:0)

在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

执行此操作时,在每个循环中,您将使用键&#34; date&#34;覆盖de值。如果您想在AllDate中拥有所有日期,则必须是JSONArray。

您也可以Alldate.put("date", SubBucket);

替换Alldate.put("date" + i, SubBucket);

答案 1 :(得分:0)

与其在类范围内声明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);

或适合您代码的内容。