0

Suppose I have the following Map<String, String> of values: v1: 2, v2: 5, v3: 0, v4: -9 ...

The keys are v1 - vn, but I don't know the exact value of n during compile-time.

How do I put all of these keys into a JSON object like so:

"item": { "v1": 2, "v2": 5, "v3": 0, "v4": -9 }

So basically I want to flatten them. Any thoughts?

giampaolo
  • 6,906
  • 5
  • 45
  • 73
Davio
  • 4,609
  • 2
  • 31
  • 58

1 Answers1

0

The JSON you want to produce is invalid, since every JSON string is an object (starts with {) or an array (starts with [). So the closest thing you can reach is something like this:

{"item": { "v1": 2, "v2": 5, "v3": 0, "v4": -9 }}

This code does exactly this with N values where N = 10

package stackoverflow.questions.q23492756;

import java.util.*;

import com.google.gson.Gson;

public class Q23492756 {

    public static void main(String[] args){
        Map<String, Object> map = new HashMap<>();

        for(int i = 0; i < 10; i++){
            map.put("v"+i, i);
        }

        Map<String, Object> newMap = new HashMap<>();
        newMap.put("item", map);

        Gson g = new Gson();
        String s = g.toJson(newMap);

        System.out.println(s);

    }

}

and this is the result (note that keys are unordered since it's a map)

{"item":{"v1":1,"v0":0,"v7":7,"v5":5,"v6":6,"v4":4,"v9":9,"v3":3,"v8":8,"v2":2}}
giampaolo
  • 6,906
  • 5
  • 45
  • 73