2013-12-12 101 views
1

我给出了一个表示类型为Map<String, String>的json对象的字符串。对一个json对象中的字符数量有限制。如果JSON对象中的字符数超过指定的限制,我必须将json对象转换为多个json对象的数组。使用Jackson Mapper进行此操作的最简单和最简单的方法是什么?Jackson:将一个JSON对象序列化为多个对象

例如: 如果此给出JSON对象是:

{ 
    "cfname":"Kob", 
    "NAME_6":"Philharmonic Youth Orchestra", 
    "NAME_5":"Pathways to Discovery: Engineering, Medicine & CSI", 
    "NAME_4":"Fashion Design Camp", 
    "IMAGE_URL_1":"http://res.cloudinary.com/pxxxxxx-jxxxxxx/image/upload/c_fill,h_230,w_260/v0000000000/vccrgwdekjkpdvpsrv4f.jpg", 
    "IMAGE_URL_2":"http://res.cloudinary.com/pxxxxxx-jxxxxxx/image/upload/c_fill,h_230,w_260/v0000000000/wlom2u5525nyjjbttazw.jpg" 
} 

如果对于一个JSON对象的字符计数限制为200。然后输出将是:

[ 
     { 
      "cfname":"Kob", 
      "NAME_6":"Philharmonic Youth Orchestra", 
      "NAME_5":"Pathways to Discovery: Engineering, Medicine & CSI", 
      "NAME_4":"Fashion Design Camp" 
     }, 
     { 
      "IMAGE_URL_1":"http://res.cloudinary.com/pxxxxxx-jxxxxxx/image/upload/c_fill,h_230,w_260/v0000000000/vccrgwdekjkpdvpsrv4f.jpg" 
     }, 
     { 
      "IMAGE_URL_2":"http://res.cloudinary.com/pxxxxxx-jxxxxxx/image/upload/c_fill,h_230,w_260/v0000000000/wlom2u5525nyjjbttazw.jpg" 
     } 
] 
  1. 我们可以假定给定的json对象中任何键值对的长度都小于给定的字符数限制。
  2. 我们应该在计数字符时忽略空格和换行符。

用例: 我必须将这些json对象作为标题添加到电子邮件中。由于每个标题值的smtp字符限制为1000。我必须将它分解成多个json对象,每个json对象将是一个标题值。

+1

样品问题也可能帮助您快速得到答案 – vels4j

+0

我会消除字符限制。限制单个对象的大小没有合乎逻辑的理由。 –

+0

你不能改变要求!我现在在这个问题中解释了我的用例。看看它。 – CodePredator

回答

0

最后,我只是使用了平凡的方法。这里是代码片段我写的,别人快速使用有用:

int     charCount = 11 + rcpt.length(); 
Map<String, String> map  = Maps.newHashMap(); 

for (Entry<String, String> e : mergeTags.entrySet()) { 
    int cnt = charCount(e); 

    if (charCount + cnt >= 987) { 
    message.addHeader(TEMPLATE_MERGEVARS_HEADER, BINDER.writeValue(map)); 
    map = Maps.newHashMap(); 
    charCount = 11 + rcpt.length(); 
    } 

    map.put(e.getKey(), e.getValue()); 
    charCount += cnt; 
} 

if (!map.isEmpty()) { 
    message.addHeader(TEMPLATE_MERGEVARS_HEADER, BINDER.writeValue(map)); 
} 

private static int charCount(Entry<String, String> e) { 
    return e.getKey().length() + e.getValue().length() + 6; 
} 

消息将包含所有的头值多图。