使用Gson从两个字符串数组生成JSON

时间:2017-04-05 09:31:29

标签: json gson

给定两个字符串数组,我想用以下结构解析它们:{" key1":" value1"," key2:value2"}

这样的事情:

override var bounds: CGRect {
    didSet {
        if webView != nil {
            var b = bounds
            b.origin.x = 0
            b.origin.y = 0

            webView.bounds = b
            webView.frame = b

            for item in webView.subviews {
                item.bounds = b

                if item.subviews.count > 0 {
                    setBounds(toSubView: item, toBounds: b)
                }
            }
        }
    }
}

func setBounds(toSubView subView: UIView, toBounds bounds: CGRect) {
    for item in subView.subviews {
        if item.subviews.count > 0 {
            setBounds(toSubView: item, toBounds: bounds)
        }

        if item.classIdentifier == "WKContentView" {
            item.bounds = bounds
        }
    }
}

结果:

Gson gson = new Gson();
String[] strings1 = {"abc", "def", " ghi"};
String[] strings2 = {"123", "456", "789"};

// Parse it ??

我怎么能这样做?

感谢。

5 个答案:

答案 0 :(得分:1)

您可以使用简单的HashMap来完成此操作。干杯:)

Map<String, String> map = new HashMap<String, String>;
Gson gson = new Gson();
String[] strings1 = {"abc", "def", " ghi"};
String[] strings2 = {"123", "456", "789"};    
for( int i=0; i<strings1.length; i++){
   map.put(strings1[i],strings2[i]);    
}
String json=gson.toJson(map);

答案 1 :(得分:1)

您可以执行以下操作(仅Gson解决方案):

String[] strings1 = { "abc", "def", " ghi" };
String[] strings2 = { "123", "456", "789" };
JsonObject json = new JsonObject();

for (int i = 0; i < strings1.length; i++) {
    json.addProperty(strings1[i], strings2[i]);
}

答案 2 :(得分:1)

试试这个:

String[] strings1 = {"abc", "def", " ghi"};
String[] strings2 = {"123", "456", "789"};

JSONObject obj = new JSONObject();
if(strings1.length == strings2.length){
for(int i=0;i<strings1.length;i++){
   obj.put(strings1[i],strings2[i]);
 }
}

答案 3 :(得分:1)

导入如下:

import com.google.gson.JsonObject;

代码如下:

String[] strings1 = { "abc", "def", " ghi" };
String[] strings2 = { "123", "456", "789" };
JsonObject jObj = new JsonObject();
for (int i = 0; i < strings1.length; i++) {
    jObj.addProperty(strings1[i], strings2[i]);
}
System.out.println("jObj : " + jObj);

答案 4 :(得分:0)

这样的事情:

  public static String constructJSON(String[] tag, String[] status) {
   GSON obj = new GSON();
    try {
        obj.put(tag[0], status[0]);
        obj.put(tag[1], status[1]);
          .................................................
    } catch (JSONException e) {
        // TODO Auto-generated catch block
    }
     return obj.toString();
}