有人能帮我写Json吗?

时间:2020-11-29 01:31:40

I m just parsing the datas from server which is in Json format. I got stucked. I don't know how to proceed further.

我只是用Json格式解析来自服务器的数据。我被卡住了。我不知道如何继续下去。

JSONObject object1 = new JSONObject(str);
String s1 = object1.getString("results");
JSONArray array1 = object1.getJSONArray("constituencies");

Is the above code right?

上面的代码对吗?

2 个解决方案

#1


0  

Have a look at to the following JSON Parsing code,

看看下面的JSON解析代码,

public class ParseJSON extends Activity {

/** Called when the activity is first created. */

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    String readTwitterFeed = readTwitterFeed();
    try {
      JSONArray jsonArray = new JSONArray(readTwitterFeed);
      Log.i(ParseJSON.class.getName(),
          "Number of entries " + jsonArray.length());
      for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        Log.i(ParseJSON.class.getName(), jsonObject.getString("text"));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public String readTwitterFeed() {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("http://twitter.com/statuses/user_timeline/vogella.json");
    try {
      HttpResponse response = client.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
          builder.append(line);
        }
      } else {
        Log.e(ParseJSON.class.toString(), "Failed to download file");
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return builder.toString();
  }
} 

Writing JSON is very simple. Just create the JSONObject or JSONArray and use the toString() method.

编写JSON非常简单。只需创建JSONObject或JSONArray并使用toString()方法。

public void writeJSON() {
  JSONObject object = new JSONObject();
  try {
    object.put("name", "Jack Hack");
    object.put("score", new Integer(200));
    object.put("current", new Double(152.32));
    object.put("nickname", "Hacker");
  } catch (JSONException e) {
    e.printStackTrace();
  }
  System.out.println(object);
}

Original Source.

最初的来源。

#2


0  

Above codes right or wrong??

以上代码是对还是错?

So look at source:

看看来源:

{
   "results":{
      "constituencies":[

      ],
      "members":[
         {
            "constituency_name":"Beckenham",
            "member_name":"Bob Stewart",
            "member_party":"Conservative",
            "member_biography_url":"http://www.parliament.uk/biographies/commons/Bob-Stewart/3919",
            "member_website":"http://www.bobstewartmp.com/",
            "uri":"http://findyourmp.parliament.uk/constituencies/beckenham.json"
         },
         {
            "constituency_name":"Colchester",
            "member_name":"Sir Bob Russell",
            "member_party":"Liberal Democrat",
            "member_biography_url":"http://www.parliament.uk/biographies/commons/Sir-Bob-Russell/35",
            "member_website":"http://www.bobrussell.org.uk",
            "uri":"http://findyourmp.parliament.uk/constituencies/colchester.json"
         },
      ]
   }
}

Here you have two JSONObject:

这里有两个JSONObject:

  • First(whole source)
  • 第一个(整个源)
  • results
  • 结果

results contains(in this snippet of code) two JSONArrays:

结果包含(在这段代码中)两个jsonarray:

  • constituencies(that is empty array)
  • 选区(即空数组)
  • members(it has two childs)
  • 成员(它有两个孩子)

So you need to first fetch whole JSON then results and then you have access to arrays.

因此,首先需要获取整个JSON,然后获取结果,然后才能访问数组。

JSONObject root = new JSONObject(str); // whole source
JSONObject results = root.getJSONObject("results");

JSONArray constituenciesArr = results.getJSONArray("constituencies");
JSONArray membersArr = results.getJSONArray("members");
JSONObject child = null;
for (int i = 0; i < membersArr.length(); i++) {
   child = membersArr.getJSONObject(i);
   String mName = child.getString("member_name");
   ...

}

#1


0  

Have a look at to the following JSON Parsing code,

看看下面的JSON解析代码,

public class ParseJSON extends Activity {

/** Called when the activity is first created. */

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    String readTwitterFeed = readTwitterFeed();
    try {
      JSONArray jsonArray = new JSONArray(readTwitterFeed);
      Log.i(ParseJSON.class.getName(),
          "Number of entries " + jsonArray.length());
      for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        Log.i(ParseJSON.class.getName(), jsonObject.getString("text"));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public String readTwitterFeed() {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("http://twitter.com/statuses/user_timeline/vogella.json");
    try {
      HttpResponse response = client.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
          builder.append(line);
        }
      } else {
        Log.e(ParseJSON.class.toString(), "Failed to download file");
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return builder.toString();
  }
} 

Writing JSON is very simple. Just create the JSONObject or JSONArray and use the toString() method.

编写JSON非常简单。只需创建JSONObject或JSONArray并使用toString()方法。

public void writeJSON() {
  JSONObject object = new JSONObject();
  try {
    object.put("name", "Jack Hack");
    object.put("score", new Integer(200));
    object.put("current", new Double(152.32));
    object.put("nickname", "Hacker");
  } catch (JSONException e) {
    e.printStackTrace();
  }
  System.out.println(object);
}

Original Source.

最初的来源。

#2


0  

Above codes right or wrong??

以上代码是对还是错?

So look at source:

看看来源:

{
   "results":{
      "constituencies":[

      ],
      "members":[
         {
            "constituency_name":"Beckenham",
            "member_name":"Bob Stewart",
            "member_party":"Conservative",
            "member_biography_url":"http://www.parliament.uk/biographies/commons/Bob-Stewart/3919",
            "member_website":"http://www.bobstewartmp.com/",
            "uri":"http://findyourmp.parliament.uk/constituencies/beckenham.json"
         },
         {
            "constituency_name":"Colchester",
            "member_name":"Sir Bob Russell",
            "member_party":"Liberal Democrat",
            "member_biography_url":"http://www.parliament.uk/biographies/commons/Sir-Bob-Russell/35",
            "member_website":"http://www.bobrussell.org.uk",
            "uri":"http://findyourmp.parliament.uk/constituencies/colchester.json"
         },
      ]
   }
}

Here you have two JSONObject:

这里有两个JSONObject:

  • First(whole source)
  • 第一个(整个源)
  • results
  • 结果

results contains(in this snippet of code) two JSONArrays:

结果包含(在这段代码中)两个jsonarray:

  • constituencies(that is empty array)
  • 选区(即空数组)
  • members(it has two childs)
  • 成员(它有两个孩子)

So you need to first fetch whole JSON then results and then you have access to arrays.

因此,首先需要获取整个JSON,然后获取结果,然后才能访问数组。

JSONObject root = new JSONObject(str); // whole source
JSONObject results = root.getJSONObject("results");

JSONArray constituenciesArr = results.getJSONArray("constituencies");
JSONArray membersArr = results.getJSONArray("members");
JSONObject child = null;
for (int i = 0; i < membersArr.length(); i++) {
   child = membersArr.getJSONObject(i);
   String mName = child.getString("member_name");
   ...

}