string s = "{"fa490c67-bdb2-4ddd-810d-894e9ceeba0e":{"top":191,"left":55,"process_to":["bd7c788d-9d2f-48da-80ad-726edb8dffb1"]},"bd7c788d-9d2f-48da-80ad-726edb8dffb1":{"top":171,"left":281,"process_to":[]}}";
前端传来的这个json,我怎么去解析它,用dynamics解析出来的不知道怎弄,或者怎么建一个dto来解析
JObject data =JsonConvert.DeserializeObject<JObject>(str);
Console.WriteLine(data["fa490c67-bdb2-4ddd-810d-894e9ceeba0e"]["top"]);
@灬丶: 我这是举个例子,也可以直接循环data
fastjson或者gson
用fastjson解析
你的问题应该是,在解析这个json的时候,即使创建一个DTO,你也不知道DTO的字段名称应该是什么(因为接收到json的key其实是一个没有规律的字符),所以不好操作。
下面是我的解析代码:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.util.Iterator;
import java.util.Map;
public class JsonUtilsTest {
@Test
public void test() throws JsonProcessingException {
String s = "{\"fa490c67-bdb2-4ddd-810d-894e9ceeba0e\":{\"top\":191,\"left\":55,\"process_to\":[\"bd7c788d-9d2f-48da-80ad-726edb8dffb1\"]},\"bd7c788d-9d2f-48da-80ad-726edb8dffb1\":{\"top\":171,\"left\":281,\"process_to\":[]}}";
ObjectMapper objectMapper = new ObjectMapper();
final JsonNode jsonNode = objectMapper.readTree(s);
// 进行迭代
final Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields();
fields.forEachRemaining(item -> {
System.out.println(item.getKey() + " => " + item.getValue());
});
// fa490c67-bdb2-4ddd-810d-894e9ceeba0e => {"top":191,"left":55,"process_to":["bd7c788d-9d2f-48da-80ad-726edb8dffb1"]}
// bd7c788d-9d2f-48da-80ad-726edb8dffb1 => {"top":171,"left":281,"process_to":[]}
// 对于value,可以封装一个dto,包含top、left、process_to三个属性
}
}