0

我将如何在 Android 中解析以下字符串?

{
    "C1": {
        "name": "first name",
        "address": "first address",
        "lat": 36.072111,
        "lng": 34.732112
    },
    "C2": {
        "name": "second name",
        "address": "second address",
        "lat": 32.02132,
        "lng": 34.000002
    },
    "C3": {
        "name": "third name",
        "address": "third address",
        "lat": 37.05435,
        "lng": 34.75703
    }
}

我无法理解。它是对象结构内的对象吗?这将如何解析?我如何找到我有多少对象?

4

4 回答 4

3

Well, got it. the solution is to first get the names of the inner-objects:

JONObject json = new JSONObject(jsonString);
JSONArray namesArray = json.names();

which will give you an JSONArray of the existing objects inside. Then run on it's objects to get each one of them:

for (int i = 0 ; i < namesArray.length() ; i ++)
{
    currentObject = json.getJSONObject(namesArray.get(i).toString());
    Log.d("TAG", "currentObject : "+currentObject.toString());          
    addCurrentObjectShopToObjectsListUsingGson(currentObject,objectsList);
}
于 2013-10-25T00:36:55.953 回答
1

您可以使用JSONObject该结构来提取内容。

一个例子如下所示:

你可以JSONArray从你的字符串中检索一个

JSONObject json = new JSONObject(jsonString);
JSONArray myArray = json.getJSONArray(ARRAY_NAME_HERE);

这样做之后,你可以提取一个人的名字

JSONObject person = myArray.getJSONObject(0); // retrieve the first person
String name = person.getString("name"); // get the person's name

参考:

http://developer.android.com/reference/org/json/JSONObject.html

于 2013-10-25T00:23:08.930 回答
0

You need a "model" object that looks like this: (provided the hash is static).

public class TheCs extends BaseModel {
    public OneC c1;
    public OneC c2;
    public OneC c3;
}

public class OneC extends BaseModel {
    public String name;
    public String address;
    public float lat, lng;
}

public class BaseModel implements Serializable {
    private static final long serialVersionUID = 1L;//use a random number here
}

Now when parsing with Gson, pass TheCs.class as the type.

If the Hash is not static you could (and Gson will do the right thing as far as I can remember), do something like:

public class TheCs extends BaseModel {
    public List<OneC> someHash;
}
于 2013-10-25T00:38:39.307 回答
0

您显示的字符串包含一个带有 3 个内部对象的外部对象。假设您想获取 C1.name。你会这样做:

JSONObject root = new JSONObject(yourString);
JSONObject c1 = root.getJSONObject("C1");
String name = c1.getString("name");

但是,我应该指出另一件事,即您使用的原始字符串很奇怪,因为它表明您真正想要的是一个数组。当然,要解析的代码会有所不同,并且涉及 JSONArray,但我认为更好的表示形式如下所示:

  [
   {"name":"first name","address":"...","lat":"...","lng":"..."},
   {"name":"second name"...},
   {"name":"third name"...}
  ]

所以在这种情况下,最外层的容器是一个 JSONArray,而不是一个对象。

于 2013-10-25T00:31:39.383 回答