vendredi 23 mars 2018

Java - convert string with random number of variables to dynamic json object

I have a string that I need to convert to json objects. String: (30,1,2,3,4,5,6,7,8,5)

Here 1,2,3,4 are temperatures in Celsius for four different cities and 5,6,7,8 are temperatures in Fahrenheit for the same four different cities. The number of cities is 4 in here but it is subjected to change at every run (since String custom is provided randomly from a different function). 30 is var1 and 5 is var2.

Desired solution:

'[{ "var1": 30, "city1": {"tempC": 1, "tempF": 5},  "city2": {"tempC": 2, "tempF": 6}, "city3": {"tempC": 3, "tempF": 7}, "city4": {"tempC": 4, "tempF": 8}, "var2": 5}]

I am declaring variable inside the for loop to create city variable dynamically which is giving me an error. I am confused as to how I can proceed further. Any help/guidance would be much appreciated!

Thanks!

Here's my code so far.

  String custom = "(30,1,2,3,4,5,6,7,8,5)";
  custom = custom.substring(1,custom.length()-1);

  JSONObject jsonSubObject = null;
  JSONObject jsonFinal = new JSONObject();
  JSONArray jsonArrayRET = new JSONArray();


  String []array2 = custom.split(",");
  String []cityArray = Arrays.copyOfRange(array2, 1, 13);

  // delete the elements from array2 that have been copied into cityArray
  for(int i = 0; i < 12; i++) {
      array2 = (String[]) ArrayUtils.remove(array2, 1);
  }

  //I need to make the number of cities dynamic that would depend on the number of elements in half an array and hence I need to create a dynamic city variable at every run
  int numCities = ((Arrays.copyOfRange(cityArray, 0, (cityArray.length + 1)/2)).length);
  for(int i = 0; i < numCities; i++){
      ArrayList<String> city[i] = new ArrayList<String>();
      city[i].add(cityArray[i]);
      city[i].add(cityArray[i+numCities]);
  }

  jsonSubObject = new JSONObject();
  jsonSubObject.put("var1", array2[0]);
  jsonSubObject.put("var2", array2[custom.length()-1]);
  //Here I need to add city[1], city[2],city[3] anmd city[4]
  jsonArrayRET.add(jsonSubObject);

  System.out.println(jsonArrayRET);




Aucun commentaire:

Enregistrer un commentaire