如何从服务器获取数据作为json数组并将其转换为java数组以在android应用程序中使用

时间:2021-02-20 17:21:26

Possible duplicate

可能重复

How to parse a JSON and turn its values into an Array?

如何解析JSON并将其值转换为数组?

[
   [
      "sn1",
      "Liquid_level",
      "85"
   ],
   [
      "sn2",
      "Liquid_level,Temperature",
      "95"
   ],
   [
      "sn2",
      "Liquid_level,Temperature",
      "50"
   ],
   [
      "sn3",
      "Liquid_level",
      "85.7"
   ],
   [
      "sn4",
      "Liquid_level",
      "90"
   ],
   [
      "sn5",
      "Volt_meter",
      "4.5"
   ],
   [
      "sn6",
      "Temperature",
      "56"
   ],
   [
      "sn8",
      "Liquid_level",
      "30"
   ]
]

This is the data i want to get to a java array (to create a dynamic table to show data).

这是我想要获取java数组的数据(用于创建显示数据的动态表)。

i can get a text value using this

我可以使用此获取文本值

String response = null;
            try {
                response = CustomHttpClient.executeHttpPost("http://test.tester.com/check.php", postParameters);
                String res=response.toString();}

3 个解决方案

#1


3  

As from How to parse a JSON and turn its values into an Array?:

从如何解析JSON并将其值转换为数组?:

for your example:

为你的例子:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

你将不得不做这样的事情:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");

this returns the array object.

这将返回数组对象。

Then iterating will be as follows:

然后迭代将如下:

    int size = the_json_array.length();
    ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
      JSONObject another_json_object = the_json_array.getJSONObject(i);
            //Blah blah blah...
            arrays.add(another_json_object);
    }

//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

//The end...

You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).

您必须确定数据是否是数组(只需检查charAt(0)是否以[character]开头。

Hope this helps.

希望这可以帮助。

Credits to https://*.com/users/251173/the-elite-gentleman

积分https://*.com/users/251173/the-elite-gentleman

#2


1  

first parse this json array and store in ArrayList

首先解析这个json数组并存储在ArrayList中

              try 
             {
                      ArrayList<String> arl= new ArrayList<String>();
                      JSONObject jobj = new JSONObject(signedData);
                      JSONArray jroot = jobj.getJSONArray("xxxxx");

              for(int i=0;i<jroot.length();i++)
              {

                  JSONObject jElement = jroot.getJSONObject(i);

                  arl.add(jElement.getString("xxxxx"));


              }


          }

          catch (Exception e)
          {
               Log.v("log", "Error parsing data " + e.toString());

          }

and then using forloop store to string Array..

然后使用forloop store来串行数组..

#3


1  

Your conversion of JSON to Java largely depends on which library you are using to perform the task. The other answers here use the org.json library, but most geeks will react violently over its usage because it's quite slow. The fastest library I know of is Jackson, but I personally prefer Google-GSON because it's fast enough and yet remains very easy to use.

您将JSON转换为Java在很大程度上取决于您用于执行任务的库。这里的其他答案使用org.json库,但大多数极客都会对其使用做出激烈反应,因为它很慢。我所知道的最快的图书馆是杰克逊,但我个人更喜欢Google-GSON,因为它足够快但仍然非常容易使用。

Looking at your sample string, you seem to have an array of arrays of strings. In Gson, you want to think of them as a Collection of a Collection of Strings. Here's the sample code:

查看示例字符串,您似乎有一个字符串数组数组。在Gson中,您希望将它们视为字符串集合的集合。这是示例代码:

import java.lang.reflect.Type;
import java.util.Collection;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


public class Main {
    public static void main(String[] args) {
        // your sample JSON string, converted to a java string
        String json = "[\n   [\n      \"sn1\",\n      \"Liquid_level\",\n      \"85\"\n   ],\n   [\n      \"sn2\",\n      \"Liquid_level,Temperature\",\n      \"95\"\n   ],\n   [\n      \"sn2\",\n      \"Liquid_level,Temperature\",\n      \"50\"\n   ],\n   [\n      \"sn3\",\n      \"Liquid_level\",\n      \"85.7\"\n   ],\n   [\n      \"sn4\",\n      \"Liquid_level\",\n      \"90\"\n   ],\n   [\n      \"sn5\",\n      \"Volt_meter\",\n      \"4.5\"\n   ],\n   [\n      \"sn6\",\n      \"Temperature\",\n      \"56\"\n   ],\n   [\n      \"sn8\",\n      \"Liquid_level\",\n      \"30\"\n   ]\n]";

        // instantiate a Gson object
        Gson gson = new Gson();

        // define the type of object you want to use it in Java, which is a collection of a collection of strings
        Type collectionType = new TypeToken<Collection<Collection<String>>>(){}.getType();

        // happiness starts here
        Collection<Collection<String>> stringArrays = gson.fromJson(json, collectionType);

        // simply print out everything
        for (Collection<String> collection : stringArrays) {
            for (String s : collection) {
                System.out.print(s + ", ");
            }
            System.out.println();
        }
    }
}

And the output:

并输出:

sn1, Liquid_level, 85, 
sn2, Liquid_level,Temperature, 95, 
sn2, Liquid_level,Temperature, 50, 
sn3, Liquid_level, 85.7, 
sn4, Liquid_level, 90, 
sn5, Volt_meter, 4.5, 
sn6, Temperature, 56, 
sn8, Liquid_level, 30, 

This is taken from the Google-GSON user guide: https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples

这取自Google-GSON用户指南:https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples

#1


3  

As from How to parse a JSON and turn its values into an Array?:

从如何解析JSON并将其值转换为数组?:

for your example:

为你的例子:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

你将不得不做这样的事情:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");

this returns the array object.

这将返回数组对象。

Then iterating will be as follows:

然后迭代将如下:

    int size = the_json_array.length();
    ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
      JSONObject another_json_object = the_json_array.getJSONObject(i);
            //Blah blah blah...
            arrays.add(another_json_object);
    }

//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

//The end...

You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).

您必须确定数据是否是数组(只需检查charAt(0)是否以[character]开头。

Hope this helps.

希望这可以帮助。

Credits to https://*.com/users/251173/the-elite-gentleman

积分https://*.com/users/251173/the-elite-gentleman

#2


1  

first parse this json array and store in ArrayList

首先解析这个json数组并存储在ArrayList中

              try 
             {
                      ArrayList<String> arl= new ArrayList<String>();
                      JSONObject jobj = new JSONObject(signedData);
                      JSONArray jroot = jobj.getJSONArray("xxxxx");

              for(int i=0;i<jroot.length();i++)
              {

                  JSONObject jElement = jroot.getJSONObject(i);

                  arl.add(jElement.getString("xxxxx"));


              }


          }

          catch (Exception e)
          {
               Log.v("log", "Error parsing data " + e.toString());

          }

and then using forloop store to string Array..

然后使用forloop store来串行数组..

#3


1  

Your conversion of JSON to Java largely depends on which library you are using to perform the task. The other answers here use the org.json library, but most geeks will react violently over its usage because it's quite slow. The fastest library I know of is Jackson, but I personally prefer Google-GSON because it's fast enough and yet remains very easy to use.

您将JSON转换为Java在很大程度上取决于您用于执行任务的库。这里的其他答案使用org.json库,但大多数极客都会对其使用做出激烈反应,因为它很慢。我所知道的最快的图书馆是杰克逊,但我个人更喜欢Google-GSON,因为它足够快但仍然非常容易使用。

Looking at your sample string, you seem to have an array of arrays of strings. In Gson, you want to think of them as a Collection of a Collection of Strings. Here's the sample code:

查看示例字符串,您似乎有一个字符串数组数组。在Gson中,您希望将它们视为字符串集合的集合。这是示例代码:

import java.lang.reflect.Type;
import java.util.Collection;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


public class Main {
    public static void main(String[] args) {
        // your sample JSON string, converted to a java string
        String json = "[\n   [\n      \"sn1\",\n      \"Liquid_level\",\n      \"85\"\n   ],\n   [\n      \"sn2\",\n      \"Liquid_level,Temperature\",\n      \"95\"\n   ],\n   [\n      \"sn2\",\n      \"Liquid_level,Temperature\",\n      \"50\"\n   ],\n   [\n      \"sn3\",\n      \"Liquid_level\",\n      \"85.7\"\n   ],\n   [\n      \"sn4\",\n      \"Liquid_level\",\n      \"90\"\n   ],\n   [\n      \"sn5\",\n      \"Volt_meter\",\n      \"4.5\"\n   ],\n   [\n      \"sn6\",\n      \"Temperature\",\n      \"56\"\n   ],\n   [\n      \"sn8\",\n      \"Liquid_level\",\n      \"30\"\n   ]\n]";

        // instantiate a Gson object
        Gson gson = new Gson();

        // define the type of object you want to use it in Java, which is a collection of a collection of strings
        Type collectionType = new TypeToken<Collection<Collection<String>>>(){}.getType();

        // happiness starts here
        Collection<Collection<String>> stringArrays = gson.fromJson(json, collectionType);

        // simply print out everything
        for (Collection<String> collection : stringArrays) {
            for (String s : collection) {
                System.out.print(s + ", ");
            }
            System.out.println();
        }
    }
}

And the output:

并输出:

sn1, Liquid_level, 85, 
sn2, Liquid_level,Temperature, 95, 
sn2, Liquid_level,Temperature, 50, 
sn3, Liquid_level, 85.7, 
sn4, Liquid_level, 90, 
sn5, Volt_meter, 4.5, 
sn6, Temperature, 56, 
sn8, Liquid_level, 30, 

This is taken from the Google-GSON user guide: https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples

这取自Google-GSON用户指南:https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples