public class MainActivity extends ActionBarActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView)findViewById(R.id.hello_world); Cat murzik = new Cat(); murzik.name = "Мурзик"; murzik.age = 9; murzik.color = Color.BLACK; GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); textView.setText(gson.toJson(murzik)); } } public class Cat { public String name; public int age; public int color; public Cat(){ } } 

The result is

 {"name":"Мурзик","color":-16777216,"age":9} 

Tell me how to get this result

  {"murzik":[{"name":"Мурзик","color":-16777216,"age":9}]} 

    2 answers 2

    In terms of collections, this line

     {"murzik":[{"name":"Мурзик","color":-16777216,"age":9}]} 

    describes a hash table, in which the key "murzik" is an array / list with your object.

    Those. You can put a list with one cat in the hash table:

     Map<String, List<Cat>> cats = new HashMap<>(); cats.put("murzik", Arrays.asList(murzik)); textView.setText(gson.toJson(cats)); 

      First, it is not clear why to do this. But if you do vlob then you need to do another class.

       class Murzik { List<Cat> murzik; } 

      But it smacks of delirium. Why do we need an array of Murzik?

      • Murzik is for example. I assumed that it was necessary to do it through ArrayList <E> but how to substitute it here? textView.setText (gson.toJson (murzik)); - qwen pm
      • @qwen can tell why this is needed? What are you trying to do? - anber
      • I need to send information to the server. The server accepts it only in this form, the problem is to bring this information to this form. - qwen pm
      • @qwen means there is some kind of example or documentation on the api server. Can you add it to the question? - anber