如何解析Xml包装json

时间:2015-11-06 06:11:45

标签: android json xml-parsing

我只是想知道如何解析服务器的以下响应。我只是想从xml中取出json。因为我知道如何解析json的响应所以,有人请指导我如何才能得到这个。

我已经看过this链接进行xml解析,但我不知道如何专门解析这个(基础给定的响应)。响应如下

    <string xmlns="http://tempuri.org/">
[{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_3@2x.png","ImageID":"3"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_4@2x.png","ImageID":"4"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_5@2x.png","ImageID":"5"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_6@2x.png","ImageID":"6"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_7@2x.png","ImageID":"7"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_8@2x.png","ImageID":"8"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_9@2x.png","ImageID":"9"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_10@2x.png","ImageID":"10"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_11@2x.png","ImageID":"11"},{"OSID":"2","PhoneVersion":"IPHONE5","PhoneOS":"IOS","ImageName":"t_12@2x.png","ImageID":"12"}]
</string>

你可以在

中看到它
<string xmlns="http://tempuri.org/">

我只是想知道如何解析这种类型的respne其余的响应,这是Json我可以自己解析json。请帮我怎么做

1 个答案:

答案 0 :(得分:2)

这应该有效我还没有测试过它

import android.util.Xml;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;

public class StringXmlParser {
    // your xml doesn't have any name spacing so make it null.
    private static final String ns = null;

    public String parse(InputStream in) throws XmlPullParserException, IOException {
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in,null);
            parser.nextTag();
            return readString(parser);
        } finally {
            in.close();
        }
    }

    private String readString(XmlPullParser parser) throws XmlPullParserException, IOException {
        parser.require(XmlPullParser.START_TAG, ns, "string");
        String jsonString = readText(parser);
        parser.require(XmlPullParser.END_TAG, ns, "string");
        return jsonString;
    }

    private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
        String result = "";
        if (parser.next() == XmlPullParser.TEXT) {
            result = parser.getText();
            parser.nextTag();
        }
        return result;
    }
}

这就是你如何使用它

StringXmlParser xmlParser = new StringXmlParser();
String jsonString;
try {
    // You need to get the input stream for the xml.
    jsonString = xmlParser.parse(inputStream);
} finally {
    if(inputStream != null) {
        inputStream.close();
    }
}