在Android中解析嵌套的JSON对象

发布于 2024-11-07 02:43:17 字数 1723 浏览 0 评论 0原文

我正在尝试解析一个 JSON 对象,其中一部分如下所示:

{
"offer":{
    "category":"Salon",
    "description":"Use this offer now to enjoy this great Salon at a 20% discount. ",
    "discount":"20",
    "expiration":"2011-04-08T02:30:00Z",
    "published":"2011-04-07T12:00:33Z",
    "rescinded_at":null,
    "title":"20% off at Jun Hair Salon",
    "valid_from":"2011-04-07T12:00:31Z",
    "valid_to":"2011-04-08T02:00:00Z",
    "id":"JUN_HAIR_1302177631",
    "business":{
        "name":"Jun Hair Salon",
        "phone":"2126192989",
        "address":{
            "address_1":"12 Mott St",
            "address_2":null,
            "city":"New York",
            "cross_streets":"Chatham Sq & Worth St",
            "state":"NY",
            "zip":"10013"
        }
    },

等等......

到目前为止,我可以通过做这种事情来非常简单地解析:

JSONObject jObject = new JSONObject(content);
JSONObject offerObject = jObject.getJSONObject("offer");
String attributeId = offerObject.getString("category");
System.out.println(attributeId);

String attributeValue = offerObject.getString("description");
System.out.println(attributeValue);

String titleValue = offerObject.getString("title");
System.out.println(titleValue);`

但是当我尝试使用“name”时:' 这不会起作用。

我尝试过:

JSONObject businessObject = jObject.getJSONObject("business");
String nameValue = businesObject.getString("name");
System.out.println(nameValue);

当我尝试这样做时,我得到“JSONObject [business] not found”。

当我尝试时:

String nameValue = offerObject.getString("name");
System.out.println(nameValue);`

正如预期的那样,我得到“未找到 JSONObject [name]”。

我在这里做错了什么?我缺少一些基本的东西......

I'm trying to parse a JSON object, part of which looks like this:

{
"offer":{
    "category":"Salon",
    "description":"Use this offer now to enjoy this great Salon at a 20% discount. ",
    "discount":"20",
    "expiration":"2011-04-08T02:30:00Z",
    "published":"2011-04-07T12:00:33Z",
    "rescinded_at":null,
    "title":"20% off at Jun Hair Salon",
    "valid_from":"2011-04-07T12:00:31Z",
    "valid_to":"2011-04-08T02:00:00Z",
    "id":"JUN_HAIR_1302177631",
    "business":{
        "name":"Jun Hair Salon",
        "phone":"2126192989",
        "address":{
            "address_1":"12 Mott St",
            "address_2":null,
            "city":"New York",
            "cross_streets":"Chatham Sq & Worth St",
            "state":"NY",
            "zip":"10013"
        }
    },

And so on....

So far, I'm able to parse very simply, by doing this kinda thing:

JSONObject jObject = new JSONObject(content);
JSONObject offerObject = jObject.getJSONObject("offer");
String attributeId = offerObject.getString("category");
System.out.println(attributeId);

String attributeValue = offerObject.getString("description");
System.out.println(attributeValue);

String titleValue = offerObject.getString("title");
System.out.println(titleValue);`

But when I try it for 'name:' it won't work.

I've tried:

JSONObject businessObject = jObject.getJSONObject("business");
String nameValue = businesObject.getString("name");
System.out.println(nameValue);

When I try that, I get "JSONObject [business] not found."

And when I try:

String nameValue = offerObject.getString("name");
System.out.println(nameValue);`

I get, as expected, "JSONObject [name] not found".

What am I doing wrong here? I'm missing something basic....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

疾风者 2024-11-14 02:43:17

好吧,我是个白痴。这有效。

JSONObject businessObject = offerObject.getJSONObject("business");
String nameValue = businessObject.getString("name");
System.out.println(nameValue);

如果我在发帖前想两秒钟就好了……天啊!

Ok, I'm an idiot. This works.

JSONObject businessObject = offerObject.getJSONObject("business");
String nameValue = businessObject.getString("name");
System.out.println(nameValue);

If I would only think for two seconds before posting... Jees!

§普罗旺斯的薰衣草 2024-11-14 02:43:17

这是单行解决方案

String myString = myJsonObject.getJSONObject("offer").getJSONObject("business").getString("name");

Here a single-line solution

String myString = myJsonObject.getJSONObject("offer").getJSONObject("business").getString("name");
橘味果▽酱 2024-11-14 02:43:17

请注意,与 Java 对象之间的 JSON 序列化/反序列化不必“手动”完成。 GSONJackson 使这变得非常容易。

import java.text.DateFormat;
import java.util.Date;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

公共课 Foo { 静态字符串 jsonInput = “{”+ "\"报价\":{" + "\"类别\":\"沙龙\"," + "\"description\":\"立即使用此优惠,以 20% 的折扣享受这个精彩的沙龙。 \"," + "\"折扣\":\"20\"," + "\"过期\":\"2011-04-08T02:30:00Z\"," + "\"发布\":\"2011-04-07T12:00:33Z\"," + "\"recinded_at\":null," + "\"title\":\"Jun Hair Salon 20% 折扣\"," + "\"valid_from\":\"2011-04-07T12:00:31Z\"," + "\"valid_to\":\"2011-04-08T02:00:00Z\"," + "\"id\":\"JUN_HAIR_1302177631\"," + "\"业务\":{" + "\"名称\":\"Jun美发沙龙\"," + "\"电话\":\"2126192989\"," + "\"地址\":{" + "\"address_1\":\"莫特街 12 号\"," + "\"address_2\":null," + "\"城市\":\"纽约\"," + "\"cross_streets\":\"查塔姆广场和值得圣\"," + "\"州\":\"NY\"," + "\"zip\":\"10013\"" + “}”+ “}”+ “}”+ “}”;

public static void main(String[] args) 抛出异常 { GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); gsonBuilder.setDateFormat(DateFormat.LONG); Gson gson = gsonBuilder.create(); OfferContainer OfferContainer = gson.fromJson(jsonInput, OfferContainer.class); System.out.println(offerContainer); } 类

OfferContainer { 私募报价;

@覆盖 公共字符串 toString() { 返回offer.toString(); } }

类优惠 { 私人类别类别; 私有字符串描述; 私人字符串折扣; 私人日期到期; 私人发布日期; 私有字符串recinded_at; 私有字符串标题; 私人日期 valid_from; 私有日期 valid_to; 私有字符串 ID; 私营企业;

@覆盖 公共字符串 toString() { 返回字符串.format( “[优惠:类别=%1$s,描述=%2$s,折扣=%3$s,到期=%4$s,已发布=%5$s,recinded_at=%6$s,标题=%7 $s,valid_from=%8$s,valid_to=%9$s,id=%10$s,业务=%11$s]", 类别、描述、折扣、过期、已发布、recinded_at、标题、valid_from、valid_to、id、 商业); } }

枚举类别 { 沙龙 }

商务舱 { 私有字符串名称; 私人字符串电话; 私人地址地址;

@覆盖 公共字符串 toString() { 返回字符串.format( "[公司:姓名=%1$s,电话=%2$s,地址=%3$s]", 姓名、电话、地址); } }

类地址 { 私有字符串地址_1; 私有字符串地址_2; 私人字符串城市; 私有字符串cross_streets; 私有字符串状态; 私有字符串 zip;

<代码>@Override 公共字符串 toString() { 返回字符串.format( "[地址:address_1=%1$s、address_2=%2$s、城市=%3$s、cross_streets=%4$s、州=%5$s、zip=%6$s]", 地址_1、地址_2、城市、cross_streets、州、邮政编码); } }

Note that a FieldNamingPolicy can be used to easily map attribute names from the JSON to the Java code. The LOWER_CASE_WITH_UNDERSCORES policy unfortunately does not work with JSON attribute names like "address_1".

如果您关心 JSON 处理的性能,请查看 Jackson Vs. Gsonhttp://www.cowtowncoder.com/博客/archives/2011/01/entry_437.html

Note that serializing/deserializing JSON to/from Java objects doesn't have to be done "manually". Libraries like GSON and Jackson make it very easy.

import java.text.DateFormat;
import java.util.Date;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Foo { static String jsonInput = "{" + "\"offer\":{" + "\"category\":\"Salon\"," + "\"description\":\"Use this offer now to enjoy this great Salon at a 20% discount. \"," + "\"discount\":\"20\"," + "\"expiration\":\"2011-04-08T02:30:00Z\"," + "\"published\":\"2011-04-07T12:00:33Z\"," + "\"rescinded_at\":null," + "\"title\":\"20% off at Jun Hair Salon\"," + "\"valid_from\":\"2011-04-07T12:00:31Z\"," + "\"valid_to\":\"2011-04-08T02:00:00Z\"," + "\"id\":\"JUN_HAIR_1302177631\"," + "\"business\":{" + "\"name\":\"Jun Hair Salon\"," + "\"phone\":\"2126192989\"," + "\"address\":{" + "\"address_1\":\"12 Mott St\"," + "\"address_2\":null," + "\"city\":\"New York\"," + "\"cross_streets\":\"Chatham Sq & Worth St\"," + "\"state\":\"NY\"," + "\"zip\":\"10013\"" + "}" + "}" + "}" + "}";

public static void main(String[] args) throws Exception { GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); gsonBuilder.setDateFormat(DateFormat.LONG); Gson gson = gsonBuilder.create(); OfferContainer offerContainer = gson.fromJson(jsonInput, OfferContainer.class); System.out.println(offerContainer); } }

class OfferContainer { private Offer offer;

@Override public String toString() { return offer.toString(); } }

class Offer { private Category category; private String description; private String discount; private Date expiration; private Date published; private String rescinded_at; private String title; private Date valid_from; private Date valid_to; private String id; private Business business;

@Override public String toString() { return String.format( "[Offer: category=%1$s, description=%2$s, discount=%3$s, expiration=%4$s, published=%5$s, rescinded_at=%6$s, title=%7$s, valid_from=%8$s, valid_to=%9$s, id=%10$s, business=%11$s]", category, description, discount, expiration, published, rescinded_at, title, valid_from, valid_to, id, business); } }

enum Category { Salon }

class Business { private String name; private String phone; private Address address;

@Override public String toString() { return String.format( "[Business: name=%1$s, phone=%2$s, address=%3$s]", name, phone, address); } }

class Address { private String address_1; private String address_2; private String city; private String cross_streets; private String state; private String zip;

@Override public String toString() { return String.format( "[Address: address_1=%1$s, address_2=%2$s, city=%3$s, cross_streets=%4$s, state=%5$s, zip=%6$s]", address_1, address_2, city, cross_streets, state, zip); } }

Note that a FieldNamingPolicy can be used to easily map attribute names from the JSON to the Java code. The LOWER_CASE_WITH_UNDERSCORES policy unfortunately does not work with JSON attribute names like "address_1".

If the performance of JSON handling is a concern, then take a look at Jackson Vs. Gson and http://www.cowtowncoder.com/blog/archives/2011/01/entry_437.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文