0

我坚持使用 org.json 在 Java 中解析 JSON。我的 JSON 看起来像这样

[{"id" : "1",
  "type" : "City",
  "description" : [ "short_description" : "some data",
                    "long_description" : "some data",
                    "postal_code" : "49045",
                    "population" : "900000",
                  ],
     }
 ],

例如,我如何解析标签描述的元素,例如 long_description ?

4

4 回答 4

1

使用json-lib,您可以简单地将其作为库添加到现有项目中,然后执行以下操作:

数据(JSON):

{'foo':'bar','coolness':2.0,'altitude':39000,'pilot':{'firstName':'Buzz','lastName':'Aldrin'},'mission':'apollo 11 '}

解析数据的代码:

import java.io.InputStream;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.apache.commons.io.IOUtils;

public class JsonParsing {

    public static void main(String[] args) throws Exception {
        InputStream is = 
                JsonParsing.class.getResourceAsStream( "sample-json.txt");
        String jsonTxt = IOUtils.toString( is );

        JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );        
        double coolness = json.getDouble( "coolness" );
        int altitude = json.getInt( "altitude" );
        JSONObject pilot = json.getJSONObject("pilot");
        String firstName = pilot.getString("firstName");
        String lastName = pilot.getString("lastName");

        System.out.println( "Coolness: " + coolness );
        System.out.println( "Altitude: " + altitude );
        System.out.println( "Pilot: " + lastName );
    }
}

参考:

于 2012-09-18T09:22:51.740 回答
0
JSONArray values = new JSONArray(yourstring);
for(int i = 0 ; i < values.length(); i++){
    JSONObject object= values.get(i);
    JSONArray desc = object.getJSONArray("description");

}
于 2012-09-18T09:23:08.233 回答
0

你可以在没有图书馆的情况下做到这一点 -

try  {
    JSONTokener tokener = new JSONTokener(yourString);
    JSONObject jsonObj = (JSONObject) tokener.nextValue();
    String output = jsonObj.getString("streamUrl");
} catch (JSONException e) {
    Log.v("Logtag", "Problem in decoding json");
    e.printStackTrace();
}
于 2012-09-18T09:29:01.673 回答
0
 //import java.util.ArrayList;
 //import org.bson.Document;


 Document root = Document.parse("{ \"foo\" : \"bar\", \"coolness\" : 2.0, \"altitude\" : 39000, \"pilot\" : { \"firstName\" : \"Buzz\", \"lastName\" : \"Aldrin\" }, \"mission\" : \"apollo 11\" }");

 System.out.println(((String)root.get("foo")));
 System.out.println((root.get("coolness")));
 System.out.println((root.get("altitude")));
 System.out.println(((String)((Document)root.get("pilot")).get("firstName")));
 System.out.println(((String)((Document)root.get("pilot")).get("lastName")));
 System.out.println(((String)root.get("mission")));
于 2019-10-04T18:03:15.523 回答