一个非常简单的问题,那里有很多例子,但没有一个适合我。
我需要解析最简单的json字符串形式:
{"id" : "5" , "name" : "John"}
如何将其转换为数组,列表,映射任何内容,以便我可以得到这样的内容?
myArray["id"] = 5
答案 0 :(得分:2)
解析json
JSONObject jsonobject = new JSONObject("mystring");
String id = jsonobject.getString("id");
String anem = jsonobject.getString("name");
解析并获取数据后,将其添加到数组或列表中,或使用类似黑带建议的DataHolder
答案 1 :(得分:1)
一个简单的解决方案可能是
public class DataHolder {
String id;
String name;
}
ArrayList<DataHolder> dataHolder = new ArrayList<DataHolder>();
while (parsing) {
holder = new DataHolder();
holder.name = name;
holder.id = id;
dataHolder.add(holder);
}
答案 2 :(得分:1)
试试这个
JSONObject rawData = new JSONObject("{\"id\" : \"5\" , \"name\" : \"John\"}");
Iterator<String> keys = rawData.keys();
HashMap<String, String> mappedData = new HashMap<String, String>();
while (keys.hasNext())
{
String key = (String) keys.next();
if(rawData.getString(key) != null && rawData.getString(key)!= null)
{
mappedData.put(key, rawData.getString(key));
}
}
现在您可以获取数据
mappedData.get("id"); // 5
mappedData.get("name") // John
答案 3 :(得分:1)
//URL to get JSON Array
private static String url = "http://x.x.x.x/JSON/";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
JSONArray user = null;
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
}
catch(Exception e)
{ System.out.println(e.getMessage()); }