将查询字符串参数解析为 java 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13281701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:06:33  来源:igfitidea点击:

Parse a query string parameter to java object

javaparsingquery-stringquerystringparameter

提问by Sonrobby

I have query string like that:

我有这样的查询字符串:

ObjectGUId=1abcde&ObjectType=2&ObjectTitle=maximumoflife&Content=racroi&TimeStamp=2012-11-05T17:20:06.056

And I have Java Object:

我有 Java 对象:

LogObject{
    private String ObjectGUId;
    private String ObjectType;
    private String ObjectTitle;
    private String Content;
    private String TimeStamp;
}

So i want to parse this query string to this java Object.

所以我想将此查询字符串解析为这个 java 对象。

I've searched and read many question but not gotten correct answer yet.

我已经搜索并阅读了很多问题,但还没有得到正确的答案。

Show me what can solve this problem.

告诉我什么可以解决这个问题。

采纳答案by Iskar Jarak

Etiquette

礼仪

  1. You really should be much more specific about what you have tried and why it didn't work.

  2. A proper code sample of your LogObjectwould really be very helpful here.

  3. Ideally, you would provide a SSCCEso others could easily test your problem themselves.

  1. 您真的应该更具体地说明您尝试过的内容以及为什么它不起作用。

  2. 您的正确代码示例在LogObject这里真的非常有帮助。

  3. 理想情况下,您将提供SSCCE,以便其他人可以轻松地自己测试您的问题。

Answer

回答

You can extract the name:value pairs like this:

您可以像这样提取名称:值对:

String toParse = "ObjectGUId=1abcde&ObjectType=2&ObjectTitle=maximumoflife&Content=racroi&TimeStamp=2012-11-05T17:20:06.056";
String[] fields = toParse.split("&");
String[] kv;

HashMap<String, String> things = new HashMap<String, String>();


for (int i = 0; i < fields.length; ++i)
{
    t = fields[i].split("=");
    if (2 == kv.length)
    {
        things.put(kv[0], kv[1]); 
    }
}

I have chosen to put them into a HashMap, but you could just as easily look at the name part (kv[0]) and choose to do something with it. For example:

我已选择将它们放入 HashMap,但您也可以很容易地查看名称部分 ( kv[0]) 并选择对其进行处理。例如:

if kv[0].equals("ObjectGUId")
{
    logObject.setGUId(kv[1]); // example mutator/setter method
}
else if //...

However, all your fields in LogObjectare private and you haven't shown us any methods, so I hope you have some way of setting them from outside... bear in mind you will need to store the pairs in a data structure of some kind (as I have done with a HashMap) if you intend to intialise a LogObjectwith all the fields rather than setting the fields after a constructor call.

但是,您的所有字段LogObject都是私有的,您还没有向我们展示任何方法,所以我希望您有某种方法可以从外部设置它们……请记住,您需要将这些对存储在某种数据结构中(就像我对 a 所做的那样HashMap)如果您打算LogObject使用所有字段初始化 a而不是在构造函数调用后设置字段。

Speaking of SSCCEs, I made one for this answer.

说到 SSCCE,我为这个答案做了一个

回答by bruno.braga

If you do not really need to push the querystring into your own class (you might want that though), instead of parsing it manually, you could use the URLDecoder, as @Sonrobby has commented:

如果您真的不需要将查询字符串推送到您自己的类中(尽管您可能想要),而不是手动解析它,您可以使用 URLDecoder,正如@Sonrobby 所评论的:

String qString = "ObjectGUId=1abcde&ObjectType=2&ObjectTitle=maximumoflife";
Uri uri = Uri.parse(URLDecoder.decode("http://dummy/?" + qString, "UTF-8"));
if (uri != null) {
    for(String key: uri.getQueryParameterNames()) {
        System.out.println("key=[" + key + "], value=[" + uri.getQueryParameter(key) + "]");
    }
}            

The "dummy" looks dirty but it is required if what you only have is the querystring values (qString). If you have the complete URL, just pass it directly to the URLDecoder, and you are done.

“虚拟”看起来很脏,但如果您只有查询字符串值(qString),则需要它。如果您有完整的 URL,只需将其直接传递给 URLDecoder,您就完成了。

回答by matt burns

Inspired by @bruno.braga, here's a way using Apache http-components. You leverage all the parsing corner cases:

受到@bruno.braga 的启发,这是一种使用 Apache http-components 的方法。您可以利用所有解析极端情况:

List<NameValuePair> params = 
    URLEncodedUtils.parse("http://example.com/?" + queryString, Charset.forName("UTF-8"));

That'll give you a List of NameValuePair objects that should be easy to work with.

这将为您提供一个应该易于使用的 NameValuePair 对象列表。