将JSON对象转换为具有键值对的Flat Obejct

时间:2017-07-28 17:07:25

标签: java json

我得到的JSON对象如下:

{
    "id": "1",
    "name": "Hw",
    "price": {
        "value": "10"
    },
    {
        "items": [{
            "id": "1"
        }]
    }
}

我想将其表示为平面地图,但我想将项目数组表示为列表。

我的输出应该如下:

{
"id": "1",
"name":"Hw",
"price":"10",
"items": ["1"]
}

有人可以建议我如何实现这一目标吗?我试过这种方法:

How to deserialize JSON into flat, Map-like structure?

以上尝试过的链接输出:

{
"id": "1",
"name":"Hw",
"price.value":"10",
"items[0].id": "1"
}

但它将数组值表示为array[0]array[1],我不需要它。我需要这个数组作为列表。

4 个答案:

答案 0 :(得分:0)

您提供的JSON无效。我认为是:

{
    "id": "1",
    "name": "Hw",
    "price": {
        "value": "10"
    },
    "items": [{
        "id": "1"
    }]
}

对于您所要求的内容,不可能有通用的解决方案。但对于这个特殊的JSON,这将(使用json-simple):

@SuppressWarnings("unchecked")
public Map<String, String> transform(String inputJSON) throws ParseException {
    Map<String, String> result = new LinkedHashMap<>();
    JSONObject inputJSONObj = (JSONObject) new JSONParser().parse(inputJSON);
    String id = inputJSONObj.getOrDefault("id", "").toString();
    String name = inputJSONObj.getOrDefault("name", "").toString();
    String price = ((JSONObject) inputJSONObj.getOrDefault("price", new JSONObject())).getOrDefault("value", "")
            .toString();
    JSONArray itemsArray = (JSONArray) inputJSONObj.getOrDefault("items", new JSONArray());
    int n = itemsArray.size();
    String[] itemIDs = new String[n];
    for (int i = 0; i < n; i++) {
        JSONObject itemObj = (JSONObject) itemsArray.get(i);
        String itemId = itemObj.getOrDefault("id", "").toString();
        itemIDs[i] = itemId;
    }
    result.put("id", id);
    result.put("name", name);
    result.put("price", price);
    result.put("items", Arrays.toString(itemIDs));
    return result;
}

答案 1 :(得分:0)

使用Gson的方法。这完全符合您的要求“将其表示为平面地图,但我希望将项目数组表示为列表”

public class ParseJson1 {
    public static void main (String[] args){
        Type type = new TypeToken<HashMap<String, Object>>() {
        }.getType();
        Gson gson = new Gson();
        String json = "{\n" +
                "           \"id\": \"1\",\n" +
                "           \"name\": \"Hw\", \n" +
                "           \"price\": {\n" +
                "               \"value\": \"10\"\n" +
                "           },\n" +
                "           \"items\": [{\n" +
                "               \"id\": \"1\"\n" +
                "           }]\n" +
                "      }\n";
        HashMap<String, Object> map = gson.fromJson(json, type);
        Object val = null;
        for(String key : map.keySet()){
            val = map.get(key);
            if(val instanceof List){
                for(Object s : (List)val){
                    System.out.println(key + ":" + s);
                }
            } else 
            System.out.println(key + ":" + map.get(key));
        }
    }
}

答案 2 :(得分:0)

您必须转换Map集合Map<String, String>中的String,这将帮助您将Map数组转换为JSON格式。

JSONObject jsonObject = new JSONObject();
Map<String, String> mapObject = new HashMap<String, String>();
mapObject.put("id", "1");
mapObject.put("name", "VBage");
mapObject.put("mobile", "654321");

jsonObject.put("myJSON", mapObject);
System.out.println(jsonObject.toString());

答案 3 :(得分:-1)

首先,JSON似乎没有正确的格式。你是说这个吗?

 public string insertUsers(string Name, string Password)
        {
                string status;

                String ConStr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;

                SqlConnection sqlCon = new SqlConnection(ConStr);    // to make a connection with DB 

                SqlCommand sqlCom = new SqlCommand("InsertUsers", sqlCon); // now in order to perform action such as insert SP, we must create command object which needs command name and conncetion only

                sqlCom.CommandType = CommandType.StoredProcedure;  // you must tell the system that insertInfo is a storedprocedure 

                SqlParameter sqlParamName = new SqlParameter("@UserName", Name);
                SqlParameter sqlParamPwd= new SqlParameter("@Password", Password);

                sqlCom.Parameters.Add(sqlParamName);
                sqlCom.Parameters.Add(sqlParamPwd);      

                try
                {
                    sqlCon.Open();

                    sqlCom.ExecuteNonQuery();   // executenonquery is used for INSERT, UPDATE, DELETE 

                    //sqlCom.ExecuteScalar();   // used to pick or read a single value from procedure
                   // Response.Write("Done");

                    sqlCon.Close();

                    status= "Success";
                }
                catch (Exception ex)
                {
                    //response.Write(ex.Message);
                    status = ex.Message;
                }
            return status;
        }

另外,由于你附加了(How to deserialize JSON into flat, Map-like structure?)的链接,我假设你想以相同的方式展平JSON,结果应该是

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">System.Web.Services.Protocols.SoapException: Server was unable to process request. ---&gt; System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
   at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.XmlTextReader.Read()
   at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
   at System.Xml.XmlReader.MoveToContent()
   at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
   at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
   at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
   at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
   at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
   at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean&amp; abortProcessing)
   --- End of inner exception stack trace ---</soap:Text></soap:Reason><soap:Detail /></soap:Fault></soap:Body></soap:Envelope>

另外,如果你只是想让项目返回一个id列表(即&#34; items&#34;:[&#34; 1&#34;]),那么获得JSON更合乎逻辑

{
    "id": "1",
    "name": "Hw",
    "price": {
        "value": "10"
    },
    "items": [{
        "id": "1"
    }]
}

您附加的链接(How to deserialize JSON into flat, Map-like structure?)提供了一个没有任何自定义的常规解决方案。它不应该知道&#34; id&#34;是要在项目上追加的值。

因此,我的第一个建议是将JSON 更改为{ id=1, name=Hw, price.value=10, items[0]=1, }

如果由于任何原因无法更改JSON,那么您需要执行一些自定义,如下所示:

{
    "id": "1",
    "name": "Hw",
    "price": {
        "value": "10"
    },
    "items": [ "1" ] // instead of "items": [{"id": "1"}]

}

尝试了解所需的格式,然后研究上述代码。它应该给你答案。