开发者

How to read the JSON String

开发者 https://www.devze.com 2023-01-31 00:49 出处:网络
Ki开发者_如何学编程ndly need your help as this really taking me long time to try. From JSP, I passed the stingnify JSON object as a String to the Java action, it like

Ki开发者_如何学编程ndly need your help as this really taking me long time to try. From JSP, I passed the stingnify JSON object as a String to the Java action, it like

String jsonDealer = [{"dealerID":"VARSSWK103","dealerName":"Dealer ABC"}, {"dealerID":"VARSSTH008","dealerName":"Dealer XYZ"}]

How I can convert this to JSON object/ or ArrayList of Dealer, so that I can retrieve the dealer ID and dealer name?

Thanks for all help...


You'll need a JSON deserializer. There are quite a few for Java listed at the bottom of the JSON.org page. As of this writing:

  • org.json.
  • org.json.me.
  • Jackson JSON Processor.
  • Json-lib.
  • JSON Tools.
  • json-simple.
  • Stringtree.
  • SOJO.
  • Restlet.
  • google-gson.

...and 10 more. :-)


First, download Google GSON.

Second, create this class:

class Dealer {
    Dealer() {}
    public void setDealerID(String dealerID) {
        this.dealerID = dealerID;
    }
    public String getDealerID() {
        return dealerID;
    }
    public void setDealerName(String dealerName) {
        this.dealerName = dealerName;
    }
    public String getDealerName() {
        return dealerName;
    }
    private String dealerID;
    private String dealerName;


}

Third, use this code:

String jsonDealer = "[{\"dealerID\":\"VARSSWK103\",\"dealerName\":\"Dealer ABC\"}, {\"dealerID\":\"VARSSTH008\",\"dealerName\":\"Dealer XYZ\"}]";

Gson gson = new Gson();

Type type = new TypeToken<List<Dealer>>(){}.getType();

List<Dealer> fromJson = gson.fromJson(jsonDealer, type);

System.out.println(fromJson.get(0).getDealerName());   // example usage


You will need a json parsing api like gson to parse the json string. Follow the simple tutorial in my website http://preciselyconcise.com/apis_and_installations/json_to_java.php


You probably need a JSON library for Java which can parse the string into an object / collection.

I'm not a Java expert myselft, but this list might have somethng suitable: http://www.json.org/java/

0

精彩评论

暂无评论...
验证码 换一张
取 消