如何在strings.xml中设置从JSON消耗的变量

时间:2017-06-14 17:13:58

标签: java android json xml textview

我正在使用类似以下的JSON

select CR.DestinationCountry,
 mm.MovementRef,
CR.DestinationDepot,
case when count(CR.DestinationDepot) >= 2 then 'yes' else 'no' end as [statement],
 Case when (CR.DestinationCountry <> 'GB') and count(CR.DestinationDepot) >= 2 then CR.DestinationDepot+'/'+CR.DestinationDepot else CR.DestinationDepot end as [DestinationDepot]
,stuff((SELECT '/' + CR2.DestinationDepot' '  FROM  dbo.cgtRout cr2
    WHERE CR.DestinationCountry <> 'GB' and CR2.RouteID = MCL.CMRRouteID  order by CR2.RouteID desc FOR XML PATH('')),1,1,'') AS [DestinationDepot2]
 FROM    dbo.MALExport AS ME
    INNER JOIN dbo.movConLink AS MCL ON ME.ConsignmentReference = MCL.ConsignmentReference
    INNER JOIN dbo.cgtRoute AS CR ON CR.RouteID = MCL.CMRRouteID
    INNER JOIN dbo.movMovement AS MM ON MM.MovementRef = ME.MovementReference
    group by cr.DestinationCountry, cr.DestinationDepot, mm.MovementRef

我希望将每个对象放在string.xml中,如下所示

[
    {
        "Id": "BT00",
        "Text": "Register"
    },
    {
        "Id": "BT01",
        "Text": "Login"
    },
    {
        "Id": "BT02",
        "Text": "Next"
    },
    {
        "Id": "BT03",
        "Text": "Yes"
    }
]

尝试使用以下文档https://developer.android.com/guide/topics/resources/string-resource.html#StringArray执行此操作,但不符合我想要完成的任务

任何人都知道如何做到这一点?

更新:所呈现答案的差异,我的案例面向Android,特别是修改文件夹的实例&#34; res&#34;

3 个答案:

答案 0 :(得分:1)

好的,为此您需要执行两个步骤。

  1. 将JSON对象数组转换为字符串数组。

  2. 将字符串数组解析为XML格式

  3. This link可以帮助迈出第一步。

    或者,您可以将JSONobject数组转换为XML。 This link可以提供帮助

答案 1 :(得分:1)

还有更多相同的问题,但对于您的问题,将JSON转换为XML的方法之一,例如:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.XML;

public class JsonToXML {

    public static void main(String args[]) throws JSONException {
        JSONArray json = new JSONArray("["
                + "    {"
                + "        \"Id\": \"BT00\","
                + "        \"Text\": \"Register\""
                + "    },"
                + "    {"
                + "        \"Id\": \"BT01\","
                + "        \"Text\": \"Login\""
                + "    },"
                + "    {"
                + "        \"Id\": \"BT02\","
                + "        \"Text\": \"Next\""
                + "    },"
                + "    {"
                + "        \"Id\": \"BT03\","
                + "        \"Text\": \"Yes\""
                + "    }"
                + "]");

        String xml = XML.toString(json);
        System.out.println(xml);
    }
}

<强>输出:

<array>
    <Text>Register</Text>
    <Id>BT00</Id>
</array>
<array>
    <Text>Login</Text>
    <Id>BT01</Id>
</array>
<array>
    <Text>Next</Text>
    <Id>BT02</Id>
</array>
<array>
    <Text>Yes</Text>
    <Id>BT03</Id>
</array>

答案 2 :(得分:1)

在运行时无法将任何字符串放入string.xml文件中。它只能从中读取。唯一的方法是先在strings.xml中声明它,然后重新编译然后运行应用程序。您应该查看其他替代方法,例如将字符串保存到SharedPreferences中,或者如果要存储此数据并使用SQLite,请使用SQLite。