简体   繁体   English

将JSON对象存储为字符串并在java中打印每个值

[英]Store JSON object as a string and print each value in java

I have a JSON object {"name":["123-abc","234-bca","567-yuio"]} with unknown length.我有一个长度未知的 JSON 对象{"name":["123-abc","234-bca","567-yuio"]} I need to store it as a string and split the commas and iterate to print only the value ie 123-abc should be printed first then 234-bca etc.. -> Input: {"name":["123-abc","234-bca","567-yuio"]} -> Output: 123-abc 234-bca 567-yuio我需要将它存储为字符串并拆分逗号并迭代以仅打印值,即 123-abc 应首先打印,然后 234-bca 等。 -> 输入: {"name":["123-abc","234-bca","567-yuio"]} -> 输出: 123-abc 234-bca 567-yuio

Please help me out as I'm new to coding.请帮助我,因为我是编码新手。 Thank You谢谢你

You can try this:你可以试试这个:

JSONObject json = (JSONObject) object;
String input = json.get("name");
//String input = "\"123-abc\",\"234-bca\",\"567-yuio\"";
String[] strArray = input.split(",");
for (String string : strArray)
    System.out.println(string.replace("\"", ""));

Here object is where you stored your JSON object.这里的对象是您存储 JSON 对象的地方。

At first, you have to split the string at the commas and you have to iterate over the split list, using eg a for-loop:首先,您必须在逗号处拆分字符串,并且必须使用例如 for 循环遍历拆分列表:

for (String val : input.substring(1, input.length() - 1).split(",")) {
    System.out.println(val.replace("\"", ""));
}

You shouldn't need to store it as a string, you can actually just pull out that array from the JSON object and iterate over it.您不需要将它存储为字符串,您实际上可以从 JSON 对象中提取该数组并对其进行迭代。

JSON obj = new JSONObject(); //Get/store your data however you'd like. I will call it obj
String[] name  = obj.get( "name" );
for (int i = 0; i < name.length; i++) { //Loop through your array and output each part
    System.out.println( name[ i ] );
}

If you need to convert the obj to a string use can use the .toString() function.如果您需要将obj转换为字符串,可以使用.toString()函数。 But the above should be the easiest way to output that data.但以上应该是输出该数据的最简单方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM