如何解析Json数组

时间:2012-07-27 05:07:45

标签: json

${
   "1":{
      "vertical_id":"1",
      "vertical_name":"Men",
      "url_key":"men",
      "meta_title":"Online Shopping For Men - Buy Mens Clothes, Footwear & Accessories At Fetise ",
      "meta_description":null,
      "meta_keywords":"mens apparel, mens clothing, mens accessories online, online mens footwear store, gadgets online for men\r\n",
      "intro_banner_path":"",
      "intro_heading":"",
      "intro_subheading":"",
      "show_products":"1",
      "featured_event_count":"8",
      "is_active":"1",
      "sort_order":"1",
      "twitter_handle":"fetise",
      "facebook_page":"fetise",
      "verticalUrl":"http:\/\/www.fetise.com\/men",
      "verticalUrlComponent":"men\/"
   },
   "2":{
      "vertical_id":"2",
      "vertical_name":"Women",
      "url_key":"women",
      "meta_title":"Online Shopping for Women - Buy Womens Clothes, Footwear & Accessories At Fetise",
      "meta_description":null,
      "meta_keywords":"online womens clothing store, womens apparels online, ladies footwear and accessories store, ladies personal care products online, womens fashion clothes\r\n",
      "intro_banner_path":"",
      "intro_heading":"",
      "intro_subheading":"",
      "show_products":"1",
      "featured_event_count":"0",
      "is_active":"1",
      "sort_order":"2",
      "twitter_handle":"FetiseWomen",
      "facebook_page":"FetiseWomen",
      "verticalUrl":"http:\/\/www.fetise.com\/women",
      "verticalUrlComponent":"women\/"
   }}

如何在java中解析这个JSON?

1 个答案:

答案 0 :(得分:0)

我同时使用了GSONJackson,最终选择了杰克逊。它更适合需要JSON解析的特定Java项目,现在看起来更灵活和/或更熟悉。

在丢弃前导$(无效的JSON)后使用杰克逊Tree Model

// input is your JSON object
ObjectMapper mapper = new ObjectMapper();

// could also use Jackson ObjectNodes:
JsonNode rootNode = mapper.readValue(input.getBytes(), JsonNode.class); 
JsonNode sub1 = rootNode.get("1");
JsonNode sub2 = rootNode.get("2");

if (sub1 != null)
{
    System.out.println("1.vertical_name: " + sub1.get("vertical_name"));
    System.out.println("1.meta_title: " + sub1.get("meta_title"));
}

if (sub2 != null)
{
    System.out.println("2.vertical_name: " + sub2.get("vertical_name"));
    System.out.println("2.meta_title: " + sub2.get("meta_title"));
}

输出:

1.vertical_name: "Men"
1.meta_title: "Online Shopping For Men - Buy Mens Clothes, Footwear & Accessories At Fetise "
2.vertical_name: "Women"
2.meta_title: "Online Shopping for Women - Buy Womens Clothes, Footwear & Accessories At Fetise"

您的输入JSON是特殊的,因为它似乎使用JSON对象作为JSON数组,外部对象具有字段1, 2, ...。所以上面的方法将JSON解析为通用JsonNode对象,尽管你也可以使用Jackson将其解析为java Maps - 参见Data Binding with Generics

导航生成的数据结构假定输入知识,即使用JsonNode.get("1");,但无论您如何表示JSON,都需要做出相同的假设。

您还可以使用JsonNode.iterator迭代未知数量的此类“索引”。如果您不知道12等的数量

,这非常有用

此外,您可以创建一个匹配每个子对象的java类,并使用Jackson在给定每个子对象的情况下创建该类的实例。请参阅Full Data Binding (POJO) Example