简体   繁体   English

在scala中将字符串转换为json格式

[英]converting a string to json format in scala

I have to convert a string to json format in scala . 我必须在scala中将字符串转换为json格式。 The string is like this: 字符串是这样的:

"classification" : "Map(Metals -> List(Cu, Co, Ni), Nonmetals -> List(N,O,C), Noblegases -> List(Ar, Kr))"

The desired json format is like this: 所需的json格式如下:

"classification" : {"Metals": [Cu, Co, Ni],
                    "Nonmetals":[N,O,C],
                    "Noblegases":[Ar, Kr]
                    }

Any quick suggestions would be appreciated. 任何快速的建议将不胜感激。

Your question is not very specific so my answer is a bit vague as well. 您的问题不是很具体,所以我的回答也有点含糊。

First you will have to parse the input string and extract the values. 首先,您将必须解析输入字符串并提取值。 I would use a combination of regular expressions and simple String operations like searching for the first occurrence of a certain character (eg colon) and splitting the string there. 我会结合使用正则表达式和简单的String操作,例如搜索某个字符(例如冒号)的首次出现并在其中拆分字符串。

In the next step you create the JSON object. 在下一步中,您将创建JSON对象。 There are several libraries out there that you can use. 您可以使用几个库。 I suggest JSON-Java/org.json or if you like to use a scala library you can use play-json . 我建议使用JSON-Java / org.json,或者如果您想使用Scala库,则可以使用play-json

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

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