MRMousavi
MRMousavi

Reputation: 3

How to Convert a Multiple Array to Json Array and add Jsons to a hashmap

I want to convert this Json String to an Array. My hashmap named "HASHMRM" this is my Json String:

[
    {"id":1,"name":"hamid"},
    {"id":2,"name":"mohamad"},
    {"id":3,"name":"ali"},
    {"id":4,"name":"john"},
    {"id":5,"name":"smith"}
]

and I wanna to convert this Json String To an Array like this

String myJsonstring ="[{"id":1,"name":"hamid"},{"id":2,"name":"mohamad"},{"id":3,"name":"ali"},{"id":4,"name":"john"},{"id":5,"name":"smith"}]";
string[] AA = Jsons.....

int i =0;
while(i<string.lenght)
{
    HASHMRM.put(AA[i].split()//First, AA[i].split()//second);
    i++;
}

Upvotes: 0

Views: 64

Answers (1)

Stanley Ko
Stanley Ko

Reputation: 3497

Use Gson.

First, you need POJO class that matches your data.

class MyUser {
    int id;
    String name;
}


Then, convert your string to List of POJO class.

// This is your string.
String myJsonString = "[{\"id\":1,\"name\":\"hamid\"},{\"id\":2,\"name\":\"mohamad\"},{\"id\":3,\"name\":\"ali\"},{\"id\":4,\"name\":\"john\"},{\"id\":5,\"name\":\"smith\"}]";

// Create new Gson object.
Gson gson = new Gson();

// Convert
List<MyUser> userList = gson.fromJson(myJsonString, new TypeToken<List<MyUser>>() {
    }.getType());


Next, use it!

for (MyUser u : userList) {
    HASHMRM.put(u.id, u.name);
} 

Remember: Instead of using the HASHMRM as variable name, I suggest you to use java conventional camel case name HashMRM.

Upvotes: 1

Related Questions